package com.ruoyi.system.api.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.OkHttpUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.*;
import com.ruoyi.system.api.domain.dto.ServiceReportDto;
import com.ruoyi.system.api.domain.dto.ServiceReportMdQuestionDto;
import com.ruoyi.system.api.domain.dto.ServiceReportServiceFeeDto;
import com.ruoyi.system.api.domain.dto.ServiceReportTrainingInformationDto;
import com.ruoyi.system.api.mapper.*;
import com.ruoyi.system.api.service.CcService;
import com.ruoyi.system.api.service.IInterfaceOperationLogService;
import okhttp3.FormBody;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.api.service.IStServiceReportService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.util.ObjectUtils;
import org.springframework.web.util.HtmlUtils;

/**
 * 服务报告 (存储服务报告和电话解决报告)Service业务层处理
 *
 * @author ruoyi
 * @date 2020-03-10
 */
@Service
public class StServiceReportServiceImpl implements IStServiceReportService {


    private static final Logger log = LoggerFactory.getLogger(StServiceReportServiceImpl.class);

    @Autowired
    private StServiceReportMapper stServiceReportMapper;

    @Autowired
    private ReportInfoMapper reportInfoMapper;

    @Autowired
    private AnnexMapper annexMapper;

    /**
     * 报告与备件的关系表
     */
    @Autowired
    private StReportPortMapper reportPortMapper;

    @Autowired
    private ServiceLogMapper serviceLogMapper;

    @Autowired
    private StCostMapper stCostMapper;
    /**
     * 调用CC接口service
     */
    @Autowired
    private CcService ccService;

    /**
     * 配置文件
     */
    @Autowired
    private Global global;

    /**
     * 接口调用日志
     */
    @Autowired
    private IInterfaceOperationLogService iInterfaceOperationLogService;

    @Autowired
    private ServiceNoticeMapper serviceNoticeMapper;
    private ReportInfo info;

    @Autowired
    private ServiceDetailsMapper serviceDetailsMapper;


    /**
     * 查询服务报告 (存储服务报告和电话解决报告)
     *
     * @param id 服务报告 (存储服务报告和电话解决报告)ID
     * @return 服务报告 (存储服务报告和电话解决报告)
     */
    @Override
    public StServiceReport selectStServiceReportById(Long id) {
        return stServiceReportMapper.selectStServiceReportById(id);
    }

    /**
     * 查询服务报告 (存储服务报告和电话解决报告)列表
     *
     * @param stServiceReport 服务报告 (存储服务报告和电话解决报告)
     * @return 服务报告 (存储服务报告和电话解决报告)
     */
    @Override
    public List<StServiceReport> selectStServiceReportList(StServiceReport stServiceReport) {
        return stServiceReportMapper.selectStServiceReportList(stServiceReport);
    }

    /**
     * 新增服务报告 (存储服务报告和电话解决报告)
     *
     * @param stServiceReport 服务报告 (存储服务报告和电话解决报告)
     * @return 结果
     */
    @Override
    public int insertStServiceReport(StServiceReport stServiceReport) {
        stServiceReport.setCreateTime(DateUtils.getNowDate());
        return stServiceReportMapper.insertStServiceReport(stServiceReport);
    }

    /**
     * 修改服务报告 (存储服务报告和电话解决报告)
     *
     * @param stServiceReport 服务报告 (存储服务报告和电话解决报告)
     * @return 结果
     */
    @Override
    public int updateStServiceReport(StServiceReport stServiceReport) {
        return stServiceReportMapper.updateStServiceReport(stServiceReport);
    }

    /**
     * 删除服务报告 (存储服务报告和电话解决报告)对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteStServiceReportByIds(String ids) {
        return stServiceReportMapper.deleteStServiceReportByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除服务报告 (存储服务报告和电话解决报告)信息
     *
     * @param id 服务报告 (存储服务报告和电话解决报告)ID
     * @return 结果
     */
    @Override
    public int deleteStServiceReportById(String id) {
        return stServiceReportMapper.deleteStServiceReportById(id);
    }

    public List<ServiceLog> getNoFlagLogList(String serviceNo, Long enginnerId) {
        // 查询关联日志
        List<ServiceLog> serviceLogs = new ArrayList<>(); //关联工作日志结果集
        List<ServiceLog> noFlagLogs = serviceLogMapper.selectServiceLogsListNoflag(serviceNo, enginnerId); //可关联的日志

        // 2020-05-20 09:59 处理日志连续 垃圾设计！f**k！
        if (null != noFlagLogs && noFlagLogs.size() > 0) {
            // 逻辑：list第一个对象直接存入结果集，从第二个开始，判断：当前的开始时间与上一个的结束时间是否<=1天，符合条件的的就是连续的
            for (int i = 0; i < noFlagLogs.size(); i++) {
                ServiceLog log = noFlagLogs.get(i);
                if (i == 0) {
                    serviceLogs.add(log);
                } else {
                    ServiceLog logBefor = noFlagLogs.get(i - 1); //相邻的上一个日志对象
                    Date endTime = logBefor.getEndTime(); //上一次的结束时间
                    Date startTime = log.getStartTime(); //本次的开始时间
                    // 计算日期差
                    double day = (startTime.getTime() - endTime.getTime()) / (60 * 60 * 1000);
                    if (day <= 24) {
                        serviceLogs.add(log);
                    } else {
                        break;
                    }
                }
            }
        }
        return serviceLogs;
    }

    /**
     * 查看服务报告详情
     *
     * @param
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/10 11:03 上午
     */
    @Override
    public ResponseWithData<?> detailServiceReport(String serviceNo, Long enginnerId, Long reportId) {
        ReportInfo reportInfo = reportInfoMapper.selectStReportInfoById(reportId);
        // 查询报告信息
        if (null == reportId) {
            // 查询关联日志
            List<ServiceLog> serviceLogs = getNoFlagLogList(serviceNo, enginnerId); //关联工作日志结果集

            reportInfo = new ReportInfo();
            StServiceReport serviceReport = new StServiceReport();
            serviceReport.setLogList(serviceLogs);
            if (null != serviceLogs && serviceLogs.size() > 0) {
                // 最早出发时间
                ServiceLog minDepartureTime = Collections.min(serviceLogs, new Comparator<ServiceLog>() {
                    @Override
                    public int compare(ServiceLog o1, ServiceLog o2) {
                        int flag = 0;
                        try {
                            if (null != o1.getDepartureTime() && null != o2.getDepartureTime()) {
                                if (o1.getDepartureTime().getTime() > o2.getDepartureTime().getTime()) {
                                    flag = 1;
                                } else if (o1.getDepartureTime().getTime() < o2.getDepartureTime().getTime()) {
                                    flag = -1;
                                } else {
                                    flag = 0;
                                }
                            } else {
                                if (null == o2.getDepartureTime() && null != o1.getDepartureTime()) {
                                    flag = -1;
                                } else if (null == o1.getDepartureTime() && null != o2.getDepartureTime()) {
                                    flag = 1;
                                } else {
                                    flag = 0;
                                }
                            }
                        } catch (Exception e) {
                            log.error("程序异常", e.getMessage());
                        }
                        return flag;
                    }
                });
                if (minDepartureTime != null) {
                    serviceReport.setStartTravelDate(minDepartureTime.getDepartureTime());
                }
                // 最小的接受任务时间
                ServiceLog minAcceptTime = Collections.min(serviceLogs, new Comparator<ServiceLog>() {
                    @Override
                    public int compare(ServiceLog o1, ServiceLog o2) {
                        int flag = 0;
                        try {
                            if (null != o1.getAcceptTime() && null != o2.getAcceptTime()) {
                                if (o1.getAcceptTime().getTime() > o2.getAcceptTime().getTime()) {
                                    flag = 1;
                                } else if (o1.getAcceptTime().getTime() < o2.getAcceptTime().getTime()) {
                                    flag = -1;
                                } else {
                                    flag = 0;
                                }
                            } else {
                                if (null == o2.getAcceptTime() && null != o1.getAcceptTime()) {
                                    flag = -1;
                                } else if (null == o1.getAcceptTime() && null != o2.getAcceptTime()) {
                                    flag = 1;
                                } else {
                                    flag = 0;
                                }
                            }
                        } catch (Exception e) {
                            log.error("程序异常", e.getMessage());
                        }
                        return flag;
                    }
                });
                if (null != minAcceptTime) {
                    serviceReport.setOrderReceivedDate(minAcceptTime.getAcceptTime());
                }
                // 最早的到达现场时间
                ServiceLog minArriveTime = Collections.min(serviceLogs, new Comparator<ServiceLog>() {
                    @Override
                    public int compare(ServiceLog o1, ServiceLog o2) {
                        int flag = 0;
                        try {
                            if (null != o1.getArriveTime() && null != o2.getArriveTime()) {
                                if (o1.getArriveTime().getTime() > o2.getArriveTime().getTime()) {
                                    flag = 1;
                                } else if (o1.getArriveTime().getTime() < o2.getArriveTime().getTime()) {
                                    flag = -1;
                                } else {
                                    flag = 0;
                                }
                            } else {
                                if (null == o2.getArriveTime() && null != o1.getArriveTime()) {
                                    flag = -1;
                                } else if (null == o1.getArriveTime() && null != o2.getArriveTime()) {
                                    flag = 1;
                                } else {
                                    flag = 0;
                                }
                            }
                        } catch (Exception e) {
                            log.error("程序异常", e.getMessage());
                        }
                        return flag;
                    }
                });
                if (null != minArriveTime) {
                    serviceReport.setOnSiteData(minArriveTime.getArriveTime());
                }
                // 最早的工作开始时间
                ServiceLog minStartTime = Collections.min(serviceLogs, new Comparator<ServiceLog>() {
                    @Override
                    public int compare(ServiceLog o1, ServiceLog o2) {
                        int flag = 0;
                        try {
                            if (null != o1.getStartTime() && null != o2.getStartTime()) {
                                if (o1.getStartTime().getTime() > o2.getStartTime().getTime()) {
                                    flag = 1;
                                } else if (o1.getStartTime().getTime() < o2.getStartTime().getTime()) {
                                    flag = -1;
                                } else {
                                    flag = 0;
                                }
                            } else {
                                if (null == o2.getStartTime() && null != o1.getStartTime()) {
                                    flag = -1;
                                } else if (null == o1.getStartTime() && null != o2.getStartTime()) {
                                    flag = 1;
                                } else {
                                    flag = 0;
                                }
                            }
                        } catch (Exception e) {
                            log.error("程序异常", e.getMessage());
                        }
                        return flag;
                    }
                });
                if (null != minStartTime) {
                    serviceReport.setStartWorkingTime(minStartTime.getStartTime());
                }
                // 最晚的工作结束时间
                ServiceLog maxEndTime = Collections.max(serviceLogs, new Comparator<ServiceLog>() {
                    @Override
                    public int compare(ServiceLog o1, ServiceLog o2) {
                        int flag = 0;
                        try {
                            if (null != o1.getEndTime() && null != o2.getEndTime()) {
                                if (o1.getEndTime().getTime() > o2.getEndTime().getTime()) {
                                    flag = 1;
                                } else if (o1.getEndTime().getTime() < o2.getEndTime().getTime()) {
                                    flag = -1;
                                } else {
                                    flag = 0;
                                }
                            } else {
                                if (null == o2.getEndTime() && null != o1.getEndTime()) {
                                    flag = -1;
                                } else if (null == o1.getEndTime() && null != o2.getEndTime()) {
                                    flag = 1;
                                } else {
                                    flag = 0;
                                }
                            }
                        } catch (Exception e) {
                            log.error("程序异常", e.getMessage());
                        }
                        return flag;
                    }
                });
                if (null != maxEndTime) {
                    serviceReport.setEndWorkingTime(maxEndTime.getEndTime());
                }
                // 总工作小时数
                Double totalWorkingHours = 0.0;
                // 总旅途小时数
                Double travelTime = 0.0;
                // 工作过程 格式：日期 + 工作日志内容
                StringBuffer actionTaken = new StringBuffer("");
                for (ServiceLog serviceLog : serviceLogs) {
                    if (null != serviceLog.getWorkHour()) {
                        totalWorkingHours += serviceLog.getWorkHour();
                    }
                    if (null != serviceLog.getJourneyHour()) {
                        travelTime += serviceLog.getJourneyHour();
                    }
                    String startTime = DateUtils.parseDateToStrEmpty("yyyy-MM-dd", serviceLog.getStartTime());
                    String workContent = StringUtils.isEmpty(serviceLog.getWorkContent()) ? "" : serviceLog.getWorkContent();
                    actionTaken.append(startTime).append("：").append(workContent).append("\n");
                }
                serviceReport.setTotalWorkingHours(totalWorkingHours);
                serviceReport.setTravelTime(travelTime);
                serviceReport.setActionTaken(actionTaken.toString());
            }
            reportInfo.setReportInfo(serviceReport);
        } else {
            reportInfo = reportInfoMapper.selectStReportInfoById(reportId);
            if (null == reportInfo) {
                return new ResponseWithData<>().success(reportInfo).code(200);
            }
            List<ServiceLog> serviceLogs = serviceLogMapper.selectServiceLogs(reportId);
            StServiceReport serviceReport = stServiceReportMapper.selectStServiceReportById(reportInfo.getBatchType());
            serviceReport.setLogList(serviceLogs);
            reportInfo.setReportInfo(serviceReport);
        }
        return new ResponseWithData<>().success(reportInfo).code(200);
    }

    /**
     * 编辑服务报告MD问题
     *
     * @param mdQuestionDto
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/10 11:16 上午
     */
    @Override
    public ResponseWithData<?> editMdQuestion(ServiceReportMdQuestionDto mdQuestionDto) {
        if (StringUtils.isEmpty(mdQuestionDto.getServiceNo())) {
            return new ResponseWithData<>().error("serviceNo cannot be empty！");
        }
        if (mdQuestionDto.getEnginnerId() == null) {
            return new ResponseWithData<>().error("enginnerId cannot be empty！");
        }
        if (StringUtils.isEmpty(mdQuestionDto.getHelpId())) {
            return new ResponseWithData<>().error("helpId cannot be empty！");
        }
        if (StringUtils.isEmpty(mdQuestionDto.getQuesOne())) {
            return new ResponseWithData<>().error("quesOne cannot be empty！");
        }
        if (StringUtils.isEmpty(mdQuestionDto.getQuesTwo())) {
            return new ResponseWithData<>().error("quesTwo cannot be empty！");
        }
        if (StringUtils.isEmpty(mdQuestionDto.getQuesThree())) {
            return new ResponseWithData<>().error("quesThree cannot be empty！");
        }
        if (StringUtils.isEmpty(mdQuestionDto.getQuesFour())) {
            return new ResponseWithData<>().error("quesFour cannot be empty！");
        }
        if (StringUtils.isEmpty(mdQuestionDto.getQuesFive())) {
            return new ResponseWithData<>().error("quesFive cannot be empty！");
        }
        if (null == mdQuestionDto.getId()) {
            StServiceReport serviceReport = new StServiceReport();
            serviceReport.setId(mdQuestionDto.getId());
            serviceReport.setServiceNo(mdQuestionDto.getServiceNo());
            serviceReport.setEnginnerId(mdQuestionDto.getEnginnerId());
            serviceReport.setHelpId(mdQuestionDto.getHelpId());
            serviceReport.setQuesOne(mdQuestionDto.getQuesOne());
            serviceReport.setQuesTwo(mdQuestionDto.getQuesTwo());
            serviceReport.setQuesThree(mdQuestionDto.getQuesThree());
            serviceReport.setQuesFour(mdQuestionDto.getQuesFour());
            serviceReport.setQuesFive(mdQuestionDto.getQuesFive());
            serviceReport.setQuesFiveone(mdQuestionDto.getQuesFiveone());
            serviceReport.setUpdateBy(mdQuestionDto.getEnginnerId() + "");
            serviceReport.setUpdateTime(new Date());
            stServiceReportMapper.insertStServiceReport(serviceReport);

            return new ResponseWithData<>().success(serviceReport).code(200);
        } else {
            StServiceReport stServiceReport = stServiceReportMapper.selectStServiceReportById(mdQuestionDto.getId());
            if (null == stServiceReport) {
                return new ResponseWithData<>().error().msg("服务报告不存在");
            }
            stServiceReport.setQuesOne(mdQuestionDto.getQuesOne());
            stServiceReport.setQuesTwo(mdQuestionDto.getQuesTwo());
            stServiceReport.setQuesThree(mdQuestionDto.getQuesThree());
            stServiceReport.setQuesFour(mdQuestionDto.getQuesFour());
            stServiceReport.setQuesFive(mdQuestionDto.getQuesFive());
            stServiceReport.setQuesFiveone(mdQuestionDto.getQuesFiveone());
            stServiceReport.setHelpId(mdQuestionDto.getHelpId());
            stServiceReport.setUpdateBy(mdQuestionDto.getEnginnerId() + "");
            stServiceReport.setUpdateTime(new Date());
            stServiceReportMapper.updateStServiceReport(stServiceReport);

            ReportInfo reportInfo = reportInfoMapper.selectStReportInfoByBatchType(stServiceReport.getId(), "1");
            if (reportInfo != null) {
                reportInfo.setServiceResult(stServiceReport.getServiceResult());
                reportInfo.setUpdateBy(mdQuestionDto.getEnginnerId() + "");
                reportInfo.setUpdateTime(new Date());
                reportInfo.setEnginnerId(mdQuestionDto.getEnginnerId());
                reportInfo.setFseName(mdQuestionDto.getFseName());
                reportInfoMapper.updateStReportInfo(reportInfo);
            }


            return new ResponseWithData<>().success(stServiceReport).code(200);
        }
    }

    /**
     * 编辑服务报告培训信息
     *
     * @param trainingInformationDto
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/10 1:13 下午
     */
    @Override
    public ResponseWithData<?> editServiceTrainingInformation(ServiceReportTrainingInformationDto trainingInformationDto) {
        if (StringUtils.isEmpty(trainingInformationDto.getServiceNo())) {
            return new ResponseWithData<>().error("serviceNo cannot be empty！");
        }
        if (trainingInformationDto.getEnginnerId() == null) {
            return new ResponseWithData<>().error("enginnerId cannot be empty！");
        }
        if (StringUtils.isEmpty(trainingInformationDto.getHelpId())) {
            return new ResponseWithData<>().error("helpId cannot be empty！");

        }
//        if (StringUtils.isEmpty(trainingInformationDto.getTrainType())) {
//            return new ResponseWithData<>().error("trainType cannot be empty！");
//        }
//        if (StringUtils.isEmpty(trainingInformationDto.getTrainNum())) {
//            return new ResponseWithData<>().error("trainNum cannot be empty！");
//        }
//        if (StringUtils.isEmpty(trainingInformationDto.getTrainFse())) {
//            return new ResponseWithData<>().error("trainFse cannot be empty！");
//        }
//        if (StringUtils.isEmpty(trainingInformationDto.getTrainFseCode())) {
//            return new ResponseWithData<>().error("trainFseCode cannot be empty！");
//        }
//        if (null == trainingInformationDto.getTrainHour()) {
//            return new ResponseWithData<>().error("trainHour cannot be empty！");
//        }
//        if (null == trainingInformationDto.getTrainStart()) {
//            return new ResponseWithData<>().error("trainStart cannot be empty！");
//        }
//        if (null == trainingInformationDto.getTrainEnd()) {
//            return new ResponseWithData<>().error("trainEnd cannot be empty！");
//        }
//        if (StringUtils.isEmpty(trainingInformationDto.getTrainPlace())) {
//            return new ResponseWithData<>().error("trainPlace cannot be empty！");
//        }
//
//        // 其他地点没有验证
//
//        if (StringUtils.isEmpty(trainingInformationDto.getTrainObject())) {
//            return new ResponseWithData<>().error("trainObject cannot be empty！");
//        }
//        if (StringUtils.isEmpty(trainingInformationDto.getCusLevel())) {
//            return new ResponseWithData<>().error("cusLevel cannot be empty！");
//        }
//        if (StringUtils.isEmpty(trainingInformationDto.getFseLevel())) {
//            return new ResponseWithData<>().error("fseLevel cannot be empty！");
//        }
//        if (StringUtils.isEmpty(trainingInformationDto.getAeFse())) {
//            return new ResponseWithData<>().error("aeFse cannot be empty！");
//        }

        if (null == trainingInformationDto.getId()) {
            StServiceReport serviceReport = new StServiceReport();
            serviceReport.setId(trainingInformationDto.getId());
            serviceReport.setServiceNo(trainingInformationDto.getServiceNo());
            serviceReport.setEnginnerId(trainingInformationDto.getEnginnerId());
            serviceReport.setHelpId(trainingInformationDto.getHelpId());
            serviceReport.setTrainType(trainingInformationDto.getTrainType());
            serviceReport.setTrainTypeName(trainingInformationDto.getTrainTypeName());
            serviceReport.setTrainNum(trainingInformationDto.getTrainNum());
            serviceReport.setTrainFse(trainingInformationDto.getFseLevel());
            serviceReport.setTrainFseCode(trainingInformationDto.getTrainFseCode());
            serviceReport.setTrainHour(trainingInformationDto.getTrainHour());
            serviceReport.setTrainStart(trainingInformationDto.getTrainStart());
            serviceReport.setTrainEnd(trainingInformationDto.getTrainEnd());
            serviceReport.setTrainPlace(trainingInformationDto.getTrainPlace());
            serviceReport.setTrainPlaceName(trainingInformationDto.getTrainPlaceName());
            serviceReport.setOtherPlace(trainingInformationDto.getOtherPlace());
            serviceReport.setTrainObject(trainingInformationDto.getTrainObject());
            serviceReport.setTrainObjectName(trainingInformationDto.getTrainObjectName());
            serviceReport.setCusLevel(trainingInformationDto.getCusLevel());
            serviceReport.setCusLevelName(trainingInformationDto.getCusLevelName());
            serviceReport.setFseLevel(trainingInformationDto.getFseLevel());
            serviceReport.setFseLevelName(trainingInformationDto.getFseLevelName());
            serviceReport.setJourHour(trainingInformationDto.getJourHour());
            serviceReport.setAeFse(trainingInformationDto.getAeFse());
            serviceReport.setUpdateBy(trainingInformationDto.getEnginnerId() + "");
            serviceReport.setTrainFse(trainingInformationDto.getTrainFse());
            serviceReport.setUpdateTime(new Date());
            stServiceReportMapper.insertStServiceReport(serviceReport);

            return new ResponseWithData<>().success(serviceReport).code(200);
        } else {
            StServiceReport stServiceReport = stServiceReportMapper.selectStServiceReportById(trainingInformationDto.getId());
            if (null == stServiceReport) {
                return new ResponseWithData<>().error().msg("服务报告不存在");
            }
            stServiceReport.setHelpId(trainingInformationDto.getHelpId());
            stServiceReport.setTrainType(trainingInformationDto.getTrainType());
            stServiceReport.setTrainTypeName(trainingInformationDto.getTrainTypeName());
            stServiceReport.setTrainNum(trainingInformationDto.getTrainNum());
            stServiceReport.setTrainFse(trainingInformationDto.getTrainFse());
            stServiceReport.setTrainFseCode(trainingInformationDto.getTrainFseCode());
            stServiceReport.setTrainHour(trainingInformationDto.getTrainHour());
            stServiceReport.setTrainStart(trainingInformationDto.getTrainStart());
            stServiceReport.setTrainEnd(trainingInformationDto.getTrainEnd());
            stServiceReport.setTrainPlace(trainingInformationDto.getTrainPlace());
            stServiceReport.setTrainPlaceName(trainingInformationDto.getTrainPlaceName());
            stServiceReport.setOtherPlace(trainingInformationDto.getOtherPlace());
            stServiceReport.setTrainObject(trainingInformationDto.getTrainObject());
            stServiceReport.setTrainObjectName(trainingInformationDto.getTrainObjectName());
            stServiceReport.setCusLevel(trainingInformationDto.getCusLevel());
            stServiceReport.setCusLevelName(trainingInformationDto.getCusLevelName());
            stServiceReport.setFseLevel(trainingInformationDto.getFseLevel());
            stServiceReport.setFseLevelName(trainingInformationDto.getFseLevelName());
            stServiceReport.setJourHour(trainingInformationDto.getJourHour());
            stServiceReport.setAeFse(trainingInformationDto.getAeFse());
            stServiceReport.setUpdateBy(trainingInformationDto.getEnginnerId() + "");
            stServiceReport.setUpdateTime(new Date());
            stServiceReportMapper.updateStServiceReport(stServiceReport);

            ReportInfo reportInfo = reportInfoMapper.selectStReportInfoByBatchType(stServiceReport.getId(), "1");
            if (reportInfo != null) {
                reportInfo.setServiceResult(stServiceReport.getServiceResult());
                reportInfo.setUpdateBy(trainingInformationDto.getEnginnerId() + "");
                reportInfo.setUpdateTime(new Date());
                reportInfo.setEnginnerId(trainingInformationDto.getEnginnerId());
                reportInfo.setFseName(trainingInformationDto.getFseName());
                reportInfoMapper.updateStReportInfo(reportInfo);
            }


            return new ResponseWithData<>().success(stServiceReport).code(200);
        }
    }

    /**
     * 编辑服务报告服务费用
     *
     * @param serviceFeeDto
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/10 1:39 下午
     */
    @Override
    public ResponseWithData<?> editServiceFee(ServiceReportServiceFeeDto serviceFeeDto) {
        double partsTotallFee = reportPortMapper.selectReportPortsPrices(serviceFeeDto.getServiceNo(), serviceFeeDto.getHelpId(), "1");

        if (StringUtils.isEmpty(serviceFeeDto.getServiceNo())) {
            return new ResponseWithData<>().error("serviceNo cannot be empty！");
        }
        if (serviceFeeDto.getEnginnerId() == null) {
            return new ResponseWithData<>().error("enginnerId cannot be empty！");
        }
        if (StringUtils.isEmpty(serviceFeeDto.getHelpId())) {
            return new ResponseWithData<>().error("helpId cannot be empty！");
        }
//        if (null == serviceFeeDto.getBasicFee()) {
//            return new ResponseWithData<>().error("basicFee cannot be empty！");
//        }
        if (null == serviceFeeDto.getManRate()) {
            serviceFeeDto.setManRate(0.0);
            //return new ResponseWithData<>().error("manRate cannot be empty！");
        }
        if (null == serviceFeeDto.getManHours()) {
            serviceFeeDto.setManHours(0.0);
            // return new ResponseWithData<>().error("manHours cannot be empty！");
        }
        if (null == serviceFeeDto.getManTotal()) {
            serviceFeeDto.setManTotal(0.0);
            //  return new ResponseWithData<>().error("manTotal cannot be empty！");
        }
        if (null == serviceFeeDto.getPartsTotallFee()) {
            serviceFeeDto.setPartsTotallFee(0.0);
            //  return new ResponseWithData<>().error("partsTotallFee cannot be empty！");
        }
        if (null == serviceFeeDto.getTotalBilled()) {
            serviceFeeDto.setTotalBilled(0.0);
            // return new ResponseWithData<>().error("totalBilled cannot be empty！");
        }
        // cc 对象
        StCost stCost = new StCost();
        stCost.setServiceNo(serviceFeeDto.getServiceNo());
        stCost.setFse(serviceFeeDto.getEnginnerId() + "");
        stCost.setHelpId(serviceFeeDto.getHelpId());
        List<StCost> stCostList = stCostMapper.selectStCostList(stCost);
        StCost curryCost = null;
        if (stCostList.size() > 0) {
            curryCost = stCostList.get(0);
        }
        if (null == serviceFeeDto.getId()) {

            if (curryCost != null) {
                StServiceReport serviceReport = new StServiceReport();
                serviceReport.setId(serviceFeeDto.getId());
                serviceReport.setFeeBalanceType(serviceFeeDto.getFeeBalanceType());
                serviceReport.setServiceNo(serviceFeeDto.getServiceNo());
                serviceReport.setEnginnerId(serviceFeeDto.getEnginnerId());
                serviceReport.setHelpId(serviceFeeDto.getHelpId());
                serviceReport.setUpdateBy(serviceFeeDto.getEnginnerId() + "");
                serviceReport.setUpdateTime(new Date());

                if ("0".equals(curryCost.getFeeBalanceType())) {
                    //detailServiceReportFee2
//                    serviceReport.setManHours(serviceFeeDto.getManHours());// 收费小时数
//                    serviceReport.setManRate(serviceFeeDto.getManRate());//单价
//                    serviceReport.setTotalPrice(serviceFeeDto.getManHours() * serviceFeeDto.getManRate());//人工费
//                    serviceReport.setTravelStayPrice(serviceFeeDto.getTravelStayPrice());
//                    double mantotal = (serviceFeeDto.getManHours() * serviceFeeDto.getManRate()) + serviceFeeDto.getTravelStayPrice();
//                    serviceReport.setManTotal(mantotal);//人工旅途费
//
//                    serviceReport.setPartsTotallFee(partsTotallFee);//备件费用
//                    serviceReport.setTotalBilled(mantotal + partsTotallFee);///报告总费用
//
//                    stServiceReportMapper.insertStServiceReport(serviceReport);

                    //detailServiceReportFee2

                    double manHours = serviceFeeDto.getManHours();
                    BigDecimal bm = new BigDecimal(manHours);
                    manHours = bm.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    serviceReport.setManHours(manHours);// 收费小时数

                    serviceReport.setManRate(serviceFeeDto.getManRate());//单价

                    double dvalue = serviceFeeDto.getManHours() * serviceFeeDto.getManRate();
                    BigDecimal b = new BigDecimal(dvalue);
                    dvalue = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    serviceReport.setTotalPrice(dvalue);//人工费

                    serviceReport.setTravelStayPrice(serviceFeeDto.getTravelStayPrice());

                    if (serviceFeeDto.getTravelStayPrice() == null) {
                        serviceFeeDto.setTravelStayPrice(0.0);
                    }
                    double mantotal = (serviceFeeDto.getManHours() * serviceFeeDto.getManRate()) + serviceFeeDto.getTravelStayPrice();
                    BigDecimal b2 = new BigDecimal(mantotal);
                    mantotal = b2.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();


                    //  double mantotal = (serviceFeeDto.getManHours() * serviceFeeDto.getManRate()) + serviceFeeDto.getTravelStayPrice();
                    serviceReport.setManTotal(mantotal);//人工旅途费
                    serviceReport.setPartsTotallFee(partsTotallFee);//备件费用

                    double mantotalTotal = mantotal + partsTotallFee;
                    BigDecimal b3 = new BigDecimal(mantotalTotal);
                    mantotalTotal = b3.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                    serviceReport.setTotalBilled(mantotalTotal);///报告总费用
                    stServiceReportMapper.insertStServiceReport(serviceReport);

                }

                if ("1".equals(curryCost.getFeeBalanceType())) {
                    double basefeeValue = 0.0;
                    if (serviceFeeDto.getChargeHours() > 0) {
                        basefeeValue = curryCost.getBasicFee();
                        serviceReport.setBasicFee(basefeeValue);// 基本费用
                    } else {
                        basefeeValue = 0;
                        serviceReport.setBasicFee(basefeeValue);// 基本费用
                    }
                    double feeHour = serviceFeeDto.getChargeHours() - curryCost.getMinHour();
                    if (feeHour < 0) {
                        feeHour = 0;
                    }
                    serviceReport.setManHours(feeHour);// 收费小时数
                    serviceReport.setManRate(serviceFeeDto.getManRate());//单价

                    double totalPrice = feeHour * serviceFeeDto.getManRate();
                    BigDecimal bm = new BigDecimal(totalPrice);
                    totalPrice = bm.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    // serviceReport.setTotalPrice(feeHour * serviceFeeDto.getManRate());//人工费
                    serviceReport.setTotalPrice(totalPrice);//人工费
                    serviceReport.setTravelStayPrice(serviceFeeDto.getTravelStayPrice());

                    double mantotal = (serviceFeeDto.getManHours() * serviceFeeDto.getManRate()) + basefeeValue;
                    BigDecimal bm1 = new BigDecimal(mantotal);
                    mantotal = bm1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    //  double mantotal = (serviceFeeDto.getManHours() * serviceFeeDto.getManRate()) + basefeeValue;

                    serviceReport.setManTotal(mantotal);//人工旅途费
                    serviceReport.setPartsTotallFee(partsTotallFee);//备件费用


                    double total = mantotal + partsTotallFee;
                    BigDecimal bm2 = new BigDecimal(total);
                    total = bm2.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    serviceReport.setTotalBilled(total);///报告总费用

                    stServiceReportMapper.insertStServiceReport(serviceReport);

                }

                if ("2".equals(curryCost.getFeeBalanceType())) {
                    double basefee = curryCost.getBasicFee();
                    if (basefee > 0) {
                        double basefeeValue = 0.0;
                        if (serviceFeeDto.getChargeHours() > 0) {
                            basefeeValue = curryCost.getBasicFee();
                            serviceReport.setBasicFee(basefeeValue);// 基本费用
                        } else {
                            basefeeValue = 0;
                            serviceReport.setBasicFee(basefeeValue);// 基本费用
                        }
                        double feeHour = serviceFeeDto.getChargeHours() - curryCost.getMinHour();
                        if (feeHour < 0) {
                            feeHour = 0;
                        }
                        serviceReport.setManHours(feeHour);// 收费小时数
                        serviceReport.setManRate(serviceFeeDto.getManRate());//单价
                        serviceReport.setTotalPrice(feeHour * serviceFeeDto.getManRate());//人工费
                        serviceReport.setTravelStayPrice(serviceFeeDto.getTravelStayPrice());

                        double mantotal = (serviceFeeDto.getManHours() * serviceFeeDto.getManRate()) + basefeeValue;
                        BigDecimal bm1 = new BigDecimal(mantotal);
                        mantotal = bm1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                        // double mantotal = (serviceFeeDto.getManHours() * serviceFeeDto.getManRate()) + basefeeValue;
                        serviceReport.setManTotal(mantotal);//人工旅途费

                        serviceReport.setPartsTotallFee(partsTotallFee);//备件费用
                        serviceReport.setEspeciallyFee(curryCost.getEspeciallyFee());

                        double total = mantotal + partsTotallFee + curryCost.getEspeciallyFee();
                        BigDecimal bm2 = new BigDecimal(total);
                        total = bm2.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                        serviceReport.setTotalBilled(total);///报告总费用

                        stServiceReportMapper.insertStServiceReport(serviceReport);

                    } else {
                        //detailServiceReportFee2
                        serviceReport.setManHours(serviceFeeDto.getManHours());// 收费小时数
                        serviceReport.setManRate(serviceFeeDto.getManRate());//单价
                        serviceReport.setTotalPrice(serviceFeeDto.getManHours() * serviceFeeDto.getManRate());//人工费

                        serviceReport.setTravelStayPrice(serviceFeeDto.getTravelStayPrice());
                        double mantotal = (serviceFeeDto.getManHours() * serviceFeeDto.getManRate()) + serviceFeeDto.getTravelStayPrice();

                        BigDecimal bm2 = new BigDecimal(mantotal);
                        mantotal = bm2.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        serviceReport.setManTotal(mantotal);//人工旅途费

                        serviceReport.setPartsTotallFee(partsTotallFee);//备件费用
                        serviceReport.setEspeciallyFee(curryCost.getEspeciallyFee());

                        double total = mantotal + partsTotallFee + curryCost.getEspeciallyFee();
                        BigDecimal bm3 = new BigDecimal(total);
                        total = bm3.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        serviceReport.setTotalBilled(total);///报告总费用

                        stServiceReportMapper.insertStServiceReport(serviceReport);
                    }

                }
                return new ResponseWithData<>().success(serviceReport).code(200);
            }

        } else {


            StServiceReport serviceReport = stServiceReportMapper.selectStServiceReportById(serviceFeeDto.getId());
            if (null == serviceReport) {
                return new ResponseWithData<>().error().msg("服务报告不存在");
            }
            if (curryCost != null) {
                serviceReport.setId(serviceFeeDto.getId());
                serviceReport.setFeeBalanceType(serviceFeeDto.getFeeBalanceType());
                serviceReport.setServiceNo(serviceFeeDto.getServiceNo());
                serviceReport.setEnginnerId(serviceFeeDto.getEnginnerId());
                serviceReport.setHelpId(serviceFeeDto.getHelpId());
                serviceReport.setUpdateBy(serviceFeeDto.getEnginnerId() + "");
                serviceReport.setUpdateTime(new Date());

                if ("0".equals(curryCost.getFeeBalanceType())) {
                    //detailServiceReportFee2
//                    serviceReport.setManHours(serviceFeeDto.getManHours());// 收费小时数
//                    serviceReport.setManRate(serviceFeeDto.getManRate());//单价
//                    serviceReport.setTotalPrice(serviceFeeDto.getManHours() * serviceFeeDto.getManRate());//人工费
//                    serviceReport.setTravelStayPrice(serviceFeeDto.getTravelStayPrice());
//                    double mantotal = (serviceFeeDto.getManHours() * serviceFeeDto.getManRate()) + serviceFeeDto.getTravelStayPrice();
//                    serviceReport.setManTotal(mantotal);//人工旅途费
//
//                    serviceReport.setPartsTotallFee(partsTotallFee);//备件费用
//                    serviceReport.setTotalBilled(mantotal + partsTotallFee);///报告总费用
//
//                    stServiceReportMapper.updateStServiceReport(serviceReport);

                    double manHours = serviceFeeDto.getManHours();
                    BigDecimal bm = new BigDecimal(manHours);
                    manHours = bm.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    serviceReport.setManHours(manHours);// 收费小时数

                    serviceReport.setManHours(manHours);// 收费小时数
                    serviceReport.setManRate(serviceFeeDto.getManRate());//单价

                    double dvalue = serviceFeeDto.getManHours() * serviceFeeDto.getManRate();
                    BigDecimal b = new BigDecimal(dvalue);
                    dvalue = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                    serviceReport.setTotalPrice(dvalue);//人工费
                    serviceReport.setTravelStayPrice(serviceFeeDto.getTravelStayPrice());

                    if (serviceFeeDto.getTravelStayPrice() == null) {
                        serviceFeeDto.setTravelStayPrice(0.0);
                    }
                    double mantotal = (serviceFeeDto.getManHours() * serviceFeeDto.getManRate()) + serviceFeeDto.getTravelStayPrice();
                    BigDecimal b2 = new BigDecimal(mantotal);
                    mantotal = b2.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                    serviceReport.setManTotal(mantotal);//人工旅途费

                    serviceReport.setPartsTotallFee(partsTotallFee);//备件费用

                    double total = mantotal + partsTotallFee;
                    BigDecimal b3 = new BigDecimal(total);
                    total = b3.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    serviceReport.setTotalBilled(total);///报告总费用

                    stServiceReportMapper.updateStServiceReport(serviceReport);


                }

                if ("1".equals(curryCost.getFeeBalanceType())) {
                    double basefeeValue = 0.0;
                    if (serviceFeeDto.getChargeHours() > 0) {
                        basefeeValue = curryCost.getBasicFee();
                        serviceReport.setBasicFee(basefeeValue);// 基本费用
                    } else {
                        basefeeValue = 0;
                        serviceReport.setBasicFee(basefeeValue);// 基本费用
                    }
                    double feeHour = serviceFeeDto.getChargeHours() - curryCost.getMinHour();
                    if (feeHour < 0) {
                        feeHour = 0;
                    }
                    serviceReport.setManHours(feeHour);// 收费小时数
                    serviceReport.setManRate(serviceFeeDto.getManRate());//单价
                    serviceReport.setTotalPrice(feeHour * serviceFeeDto.getManRate());//人工费
                    serviceReport.setTravelStayPrice(serviceFeeDto.getTravelStayPrice());

                    double mantotal = (serviceFeeDto.getManHours() * serviceFeeDto.getManRate()) + basefeeValue;
                    BigDecimal bm2 = new BigDecimal(mantotal);
                    mantotal = bm2.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    serviceReport.setManTotal(mantotal);//人工旅途费

                    serviceReport.setPartsTotallFee(partsTotallFee);//备件费用

                    double total = mantotal + partsTotallFee;
                    BigDecimal bm3 = new BigDecimal(total);
                    total = bm3.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                    serviceReport.setTotalBilled(total);///报告总费用

                    stServiceReportMapper.updateStServiceReport(serviceReport);

                }

                if ("2".equals(curryCost.getFeeBalanceType())) {
                    double basefee = curryCost.getBasicFee();
                    if (basefee > 0) {
                        double basefeeValue = 0.0;
                        if (serviceFeeDto.getChargeHours() > 0) {
                            basefeeValue = curryCost.getBasicFee();
                            serviceReport.setBasicFee(basefeeValue);// 基本费用
                        } else {
                            basefeeValue = 0;
                            serviceReport.setBasicFee(basefeeValue);// 基本费用
                        }
                        double feeHour = serviceFeeDto.getChargeHours() - curryCost.getMinHour();
                        if (feeHour < 0) {
                            feeHour = 0;
                        }
                        serviceReport.setManHours(feeHour);// 收费小时数
                        serviceReport.setManRate(serviceFeeDto.getManRate());//单价
                        serviceReport.setTotalPrice(feeHour * serviceFeeDto.getManRate());//人工费
                        serviceReport.setTravelStayPrice(serviceFeeDto.getTravelStayPrice());

                        double mantotal = (serviceFeeDto.getManHours() * serviceFeeDto.getManRate()) + basefeeValue;
                        BigDecimal bm3 = new BigDecimal(mantotal);
                        mantotal = bm3.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        serviceReport.setManTotal(mantotal);//人工旅途费

                        serviceReport.setPartsTotallFee(partsTotallFee);//备件费用
                        serviceReport.setEspeciallyFee(curryCost.getEspeciallyFee());

                        double total = mantotal + partsTotallFee + curryCost.getEspeciallyFee();
                        BigDecimal bm4 = new BigDecimal(total);
                        total = bm4.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                        serviceReport.setTotalBilled(total);///报告总费用
                        stServiceReportMapper.updateStServiceReport(serviceReport);

                    } else {

                        serviceReport.setManHours(serviceFeeDto.getManHours());// 收费小时数
                        serviceReport.setManRate(serviceFeeDto.getManRate());//单价
                        serviceReport.setTotalPrice(serviceFeeDto.getManHours() * serviceFeeDto.getManRate());//人工费

                        serviceReport.setTravelStayPrice(serviceFeeDto.getTravelStayPrice());
                        double mantotal = (serviceFeeDto.getManHours() * serviceFeeDto.getManRate()) + serviceFeeDto.getTravelStayPrice();
                        BigDecimal bm4 = new BigDecimal(mantotal);
                        mantotal = bm4.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        serviceReport.setManTotal(mantotal);//人工旅途费

                        serviceReport.setPartsTotallFee(partsTotallFee);//备件费用
                        serviceReport.setEspeciallyFee(curryCost.getEspeciallyFee());

                        double total = mantotal + partsTotallFee + curryCost.getEspeciallyFee();
                        BigDecimal bm5 = new BigDecimal(total);
                        total = bm5.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                        serviceReport.setTotalBilled(total);///报告总费用

                        stServiceReportMapper.updateStServiceReport(serviceReport);
                    }
                }

//            stServiceReport.setHelpId(serviceFeeDto.getHelpId());
//            stServiceReport.setBasicFee(serviceFeeDto.getBasicFee());
//            stServiceReport.setManRate(serviceFeeDto.getManRate());
//            stServiceReport.setManHours(serviceFeeDto.getManHours());
//            stServiceReport.setManTotal(serviceFeeDto.getManTotal());
//            stServiceReport.setPartsTotallFee(serviceFeeDto.getPartsTotallFee());
//            stServiceReport.setTotalBilled(serviceFeeDto.getTotalBilled());
//            stServiceReport.setTotalPrice(serviceFeeDto.getTotalPrice());
//            stServiceReport.setTravelStayPrice(serviceFeeDto.getTravelStayPrice());
//            stServiceReport.setUpdateBy(serviceFeeDto.getEnginnerId() + "");
//            stServiceReport.setUpdateTime(new Date());
//            stServiceReport.setEspeciallyFee(serviceFeeDto.getEspeciallyFee());
//            stServiceReport.setFeeBalanceType(serviceFeeDto.getFeeBalanceType());
//            stServiceReportMapper.updateStServiceReport(stServiceReport);


                ReportInfo reportInfo = reportInfoMapper.selectStReportInfoByBatchType(serviceReport.getId(), "1");
                if (reportInfo != null) {
                    reportInfo.setServiceResult(serviceReport.getServiceResult());
                    reportInfo.setUpdateBy(serviceFeeDto.getEnginnerId() + "");
                    reportInfo.setUpdateTime(new Date());
                    reportInfo.setEnginnerId(serviceFeeDto.getEnginnerId());
                    reportInfo.setFseName(serviceFeeDto.getFseName());
                    reportInfoMapper.updateStReportInfo(reportInfo);
                }

                return new ResponseWithData<>().success(serviceReport).code(200);
            }

        }
        return new ResponseWithData<>().success(null).code(200);
    }

    /**
     * 编辑服务报告首页内容
     *
     * @param reportDto
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/10 2:20 下午
     */
    @Override
    public ResponseWithData<?> editServiceReport(ServiceReportDto reportDto) {
        if (StringUtils.isEmpty(reportDto.getServiceNo())) {
            return new ResponseWithData<>().error("serviceNo cannot be empty！");
        }
        if (reportDto.getEnginnerId() == null) {
            return new ResponseWithData<>().error("enginnerId cannot be empty！");
        }
        if (StringUtils.isEmpty(reportDto.getHelpId())) {
            return new ResponseWithData<>().error("helpId cannot be empty！");
        }

        if (null == reportDto.getId()) {  //新增

            // 验证是否存在已完成的报告（服务报告或电话解决报告）
            List<ReportInfo> datas = reportInfoMapper.selectSubmitFinishStReportInfoByServiceNo(reportDto.getId(), reportDto.getServiceNo());
            if (StringUtils.isNotEmpty(datas)) {
                return new ResponseWithData<>().error("已存在已完成报告");
            }

            //  验证是未提交的报告（服务报告或电话解决报告）
            List<ReportInfo> checkdatas = reportInfoMapper.checkFinishStReportInfoByServiceNo(reportDto.getServiceNo());
            if (StringUtils.equals("1", reportDto.getServiceResult())) {
                if (StringUtils.isNotEmpty(checkdatas)) {
                    if (checkdatas.size() > 1) {
                        return new ResponseWithData<>().error("已存在未提交的草稿报告");
                    }
                    if (checkdatas.size() == 1 && checkdatas.get(0).getRelServiceNo() != 1) {
                        return new ResponseWithData<>().error("已存在未提交的草稿报告");
                    }
                }
            }

            StServiceReport serviceReport = new StServiceReport();
            serviceReport.setId(reportDto.getId());
            serviceReport.setServiceNo(reportDto.getServiceNo());
            serviceReport.setEnginnerId(reportDto.getEnginnerId());
            serviceReport.setHelpId(reportDto.getHelpId());
            serviceReport.setServiceType(reportDto.getServiceType());
            serviceReport.setServiceTypeName(reportDto.getServiceTypeName());
            serviceReport.setProblem(reportDto.getProblem());
            serviceReport.setStartTravelDate(reportDto.getStartTravelDate());
            serviceReport.setOrderReceivedDate(reportDto.getOrderReceivedDate());
            serviceReport.setOnSiteData(reportDto.getOnSiteData());
            serviceReport.setStartWorkingTime(reportDto.getStartWorkingTime());
            serviceReport.setEndWorkingTime(reportDto.getEndWorkingTime());
            serviceReport.setTotalWorkingHours(reportDto.getTotalWorkingHours());
            serviceReport.setTravelTime(reportDto.getTravelTime());
            serviceReport.setActionTaken(reportDto.getActionTaken());
            serviceReport.setChargeHours(reportDto.getChargeHours());
            serviceReport.setResults(reportDto.getResults());
            serviceReport.setEngineersAdvis(reportDto.getEngineersAdvis());
            serviceReport.setEnProblemDescription(reportDto.getEnProblemDescription());
            serviceReport.setServiceResult(reportDto.getServiceResult());
            serviceReport.setServiceResultName(reportDto.getServiceResultName());
            serviceReport.setSuspendType(reportDto.getSuspendType());
            serviceReport.setSuspendTypeName(reportDto.getSuspendTypeName());
            serviceReport.setSubSuspendType(reportDto.getSubSuspendType());
            serviceReport.setSubSuspendTypeName(reportDto.getSubSuspendTypeName());
            serviceReport.setWorkSuspendReason(reportDto.getWorkSuspendReason());
            serviceReport.setConcernReason(reportDto.getConcernReason());
            serviceReport.setEqSign(reportDto.getEqSign());
            serviceReport.setCreateBy(reportDto.getEnginnerId() + "");
            serviceReport.setCreateTime(new Date());
            serviceReport.setReceiver(reportDto.getReceiver());
            serviceReport.setReceiverPhone(reportDto.getReceiverPhone());
            serviceReport.setReceiverMobile(reportDto.getReceiverMobile());
            serviceReport.setReceiverEmail(reportDto.getReceiverEmail());
            updateServiceNotice(reportDto);
            // 计算费用

            //////////////////////////////草稿保存新增//////////////////////////
            double partsTotallFee = reportPortMapper.selectReportPortsPrices(reportDto.getServiceNo(), reportDto.getHelpId(), "1");
            StCost cost = addCCFree(reportDto);
            if (cost != null) {
                if ("0".equals(cost.getFeeBalanceType())) {
                    serviceReport.setManHours(0.0);// 收费小时数
                    serviceReport.setManRate(0.0);//单价
                    serviceReport.setTotalPrice(0.0);//人工费
                    serviceReport.setTravelStayPrice(0.0);
                    double mantotal = 0.0;
                    serviceReport.setManTotal(mantotal);//人工旅途费

                    serviceReport.setPartsTotallFee(partsTotallFee);//备件费用
                    serviceReport.setTotalBilled(mantotal + partsTotallFee);///报告总费用
                    //stServiceReportMapper.updateStServiceReport(stServiceReport);
                }
                if ("1".equals(cost.getFeeBalanceType())) {
                    double basefeeValue = 0.0;
                    if (reportDto.getChargeHours() > 0) {
                        basefeeValue = cost.getBasicFee();
                        serviceReport.setBasicFee(basefeeValue);// 基本费用
                    } else {
                        basefeeValue = 0;
                        serviceReport.setBasicFee(basefeeValue);// 基本费用
                    }
                    double feeHour = reportDto.getChargeHours() - cost.getMinHour();
                    if (feeHour < 0) {
                        feeHour = 0;
                    }
                    serviceReport.setManHours(feeHour);// 收费小时数
                    serviceReport.setManRate(cost.getHourFee());//单价
                    serviceReport.setTotalPrice(feeHour * cost.getHourFee());//人工费

                    double mantotal = (serviceReport.getManHours() * serviceReport.getManRate()) + basefeeValue;
                    serviceReport.setManTotal(mantotal);//人工旅途费

                    serviceReport.setPartsTotallFee(partsTotallFee);//备件费用
                    serviceReport.setTotalBilled(mantotal + partsTotallFee);///报告总费用
                }

                if ("2".equals(cost.getFeeBalanceType())) {
                    double basefee = cost.getBasicFee();
                    if (basefee > 0) {
                        double basefeeValue = 0.0;
                        if (reportDto.getChargeHours() > 0) {
                            basefeeValue = cost.getBasicFee();
                            serviceReport.setBasicFee(basefeeValue);// 基本费用
                        } else {
                            basefeeValue = 0;
                            serviceReport.setBasicFee(basefeeValue);// 基本费用
                        }
                        double feeHour = reportDto.getChargeHours() - cost.getMinHour();
                        if (feeHour < 0) {
                            feeHour = 0;
                        }
                        serviceReport.setManHours(feeHour);// 收费小时数
                        serviceReport.setManRate(cost.getHourFee());//单价
                        serviceReport.setTotalPrice(feeHour * cost.getHourFee());//人工费
                        double mantotal = (serviceReport.getManHours() * serviceReport.getManRate()) + basefeeValue;
                        serviceReport.setManTotal(mantotal);//人工旅途费

                        serviceReport.setPartsTotallFee(partsTotallFee);//备件费用
                        serviceReport.setEspeciallyFee(cost.getEspeciallyFee());
                        serviceReport.setTotalBilled(mantotal + partsTotallFee + cost.getEspeciallyFee());///报告总费用

                    } else {
                        //detailServiceReportFee2
                        serviceReport.setManHours(0.0);// 收费小时数
                        serviceReport.setManRate(0.0);//单价
                        serviceReport.setTotalPrice(0.0);//人工费
                        serviceReport.setTravelStayPrice(0.0);
                        double mantotal = 0.0;
                        serviceReport.setManTotal(mantotal);//人工旅途费

                        serviceReport.setPartsTotallFee(partsTotallFee);//备件费用
                        serviceReport.setEspeciallyFee(cost.getEspeciallyFee());
                        serviceReport.setTotalBilled(mantotal + partsTotallFee + cost.getEspeciallyFee());///报告总费用
                    }
                }
            }


            // 只要数量/天/小时大于0才参与计算
//            JSONObject checkServiceEspecial = ccService.CheckServiceEspecial(reportDto.getServiceNo());
//            String feeBalanceType = "";
//            double especiallyFee = 0;
//            boolean sign = false;
//            if ("1".equals(checkServiceEspecial.getString("status"))) {
//                JSONObject check = (JSONObject) checkServiceEspecial.getJSONArray("record").get(0);
//                feeBalanceType = check.getString("FeeBalanceType") == null ? "" : check.getString("FeeBalanceType");
//                especiallyFee = check.getDouble("EspeciallyFee") == null ? 0 : check.getDouble("EspeciallyFee");
//                if ("1".equals(feeBalanceType) || "2".equals(feeBalanceType)) {
//                    sign = true;
//                }
//            }
//            if (sign && reportDto.getChargeHours() >= 0) {
//                JSONObject response = ccService.GetServiceCharge(reportDto.getEnginnerId() + "", reportDto.getBu(), reportDto.getProv(), reportDto.getCity());
//                // 如果等于1有值，否则没有值
//                if ("1".equals(response.getString("status"))) {
//                    JSONObject jsonObject = response.getJSONArray("record").getJSONObject(0);
//                    double hourFee = jsonObject.getDouble("hour_fee");
//                    double basicFee = jsonObject.getDouble("basic_fee");
//                    double minHour = jsonObject.getDouble("min_hour");
//                    double partsTotallFee = reportPortMapper.selectReportPortsPrices(reportDto.getServiceNo(), reportDto.getHelpId(), "1");
//
//
//                    // 显示字段1：Labor 人工——Quantity数量/Day天/Hour 小时 = 报告中的收费小时数-min_hour = 3-2 =1
//                    double newMinHout;
//                    // 显示字段2：Labor 人工——Rate 单价 = hour_fee = 640
//                    double newRate = hourFee;
//                    // 显示字段3：Labor 人工——Total 总计 = 1*640 =640
//                    double newTotal;
//                    // 显示字段4：Basic Price 基本费 = basic_fee = 1280
//                    double newBasicPrice = basicFee;
//                    // 显示字段5：Travel and Labor 旅途和人工费 = "Labor 人工——Total 总计"+"Basic Price 基本费" = 640+1280 = 1920
//                    double newTravelAndLabor;
//
//                    newMinHout = (reportDto.getChargeHours() - minHour) < 0 ? 0 : (reportDto.getChargeHours() - minHour);
//                    newTotal = newMinHout * newRate;
//                    newTravelAndLabor = newTotal + newBasicPrice;
//
//                    // 显示字段6：Total to be billed 总费用（含13%税）= 报告中的备件总费用+”Travel and Labor 旅途和人工费“ +“特殊费用” = 111+1920+0 = 2031
//                    double newTotalToBeBilled = partsTotallFee + newTravelAndLabor + especiallyFee;
//                    serviceReport.setMinHour(minHour);
//                    serviceReport.setManHours((int) newMinHout);
//                    serviceReport.setBasicFee(newBasicPrice);
//                    serviceReport.setManRate(newRate);
//                    serviceReport.setTotalPrice(newTotal);
//                    serviceReport.setTotalBilled(newTotalToBeBilled);
//                    serviceReport.setManTotal(newTravelAndLabor);
//                    serviceReport.setPartsTotallFee(partsTotallFee);
//                    serviceReport.setFeeBalanceType(feeBalanceType);
//                }
//            }


            stServiceReportMapper.insertStServiceReport(serviceReport);

            // 服务报告信息插入主表st_report_info
            ReportInfo reportInfo = new ReportInfo();
            reportInfo.setServiceNo(serviceReport.getServiceNo());
            reportInfo.setEnginnerId(serviceReport.getEnginnerId());
            reportInfo.setPlanId(reportDto.getPlanId());
            reportInfo.setRelServiceNo(1L);
            reportInfo.setRelPlanId("st_service_report");
            reportInfo.setBatchType(serviceReport.getId());
            reportInfo.setDelFlag("0");
            reportInfo.setCreateTime(new Date());
            reportInfo.setCreateBy(serviceReport.getEnginnerId() + "");
            reportInfo.setNoticeId(reportDto.getNoticeId());
            reportInfo.setSyncFlag("0");
            reportInfo.setFseName(reportDto.getFseName());
            reportInfo.setServiceResult(serviceReport.getServiceResult());
            reportInfoMapper.insertStReportInfo(reportInfo);

            // 关联日志
//            List<ServiceLog> serviceLogs = serviceLogMapper.selectServiceLogsList(serviceReport.getServiceNo(), serviceReport.getEnginnerId()); // 查询关联日志
            List<ServiceLog> serviceLogs = getNoFlagLogList(serviceReport.getServiceNo(), serviceReport.getEnginnerId());
            if (null != serviceLogs) {
                for (ServiceLog serviceLog : serviceLogs) {
                    serviceLog.setReportId(reportInfo.getId().toString());
                    serviceLog.setUpdateTime(new Date());
                    serviceLogMapper.updateServiceLog(serviceLog);
                }
            }

            // 更新附件图片信息
            Annex annex = new Annex();
            annex.setHelpId(serviceReport.getHelpId());
            annex.setRelationId(serviceReport.getId().toString());
            annex.setServiceNo(serviceReport.getServiceNo());
            annex.setTblName("st_service_report");
            annex.setUpdateTime(new Date());
            annexMapper.updateAnnexByHelpIdAndServiceNo(annex);

            // 更新备件信息
            reportPortMapper.updatePhoneReportPortByHelpIdAndServiceNo(serviceReport.getId(), serviceReport.getHelpId(), serviceReport.getServiceNo());
            //更新CC备件信息
            deleteCCReportPart(serviceReport);
            reportInfo.setReportInfo(serviceReport);
            return new ResponseWithData<>().success(reportInfo).code(200);
        } else {
            StServiceReport stServiceReport = stServiceReportMapper.selectStServiceReportById(reportDto.getId());
            if (null == stServiceReport) {
                return new ResponseWithData<>().error().msg("服务报告不存在");
            }

            // 验证是未提交的报告（服务报告或电话解决报告）
//            List<ReportInfo> checkdatas = reportInfoMapper.selectFinishStReportInfoByServiceNo(reportDto.getId(), reportDto.getServiceNo());
//            if (StringUtils.isNotEmpty(checkdatas)) {
//                return new ResponseWithData<>().error("已存在未提交的草稿报告");
//            }

            stServiceReport.setHelpId(reportDto.getHelpId());
            stServiceReport.setServiceType(reportDto.getServiceType());
            stServiceReport.setServiceTypeName(reportDto.getServiceTypeName());
            stServiceReport.setProblem(reportDto.getProblem());
            stServiceReport.setStartTravelDate(reportDto.getStartTravelDate());
            stServiceReport.setOrderReceivedDate(reportDto.getOrderReceivedDate());
            stServiceReport.setOnSiteData(reportDto.getOnSiteData());
            stServiceReport.setEnginnerId(reportDto.getEnginnerId());
            stServiceReport.setStartWorkingTime(reportDto.getStartWorkingTime());
            stServiceReport.setEndWorkingTime(reportDto.getEndWorkingTime());
            stServiceReport.setTotalWorkingHours(reportDto.getTotalWorkingHours());
            stServiceReport.setTravelTime(reportDto.getTravelTime());
            stServiceReport.setActionTaken(reportDto.getActionTaken());
            stServiceReport.setChargeHours(reportDto.getChargeHours());
            stServiceReport.setResults(reportDto.getResults());
            stServiceReport.setEngineersAdvis(reportDto.getEngineersAdvis());
            stServiceReport.setEnProblemDescription(reportDto.getEnProblemDescription());
            stServiceReport.setServiceResult(reportDto.getServiceResult());
            stServiceReport.setServiceResultName(reportDto.getServiceResultName());
            stServiceReport.setSuspendType(reportDto.getSuspendType());
            stServiceReport.setSuspendTypeName(reportDto.getSuspendTypeName());
            stServiceReport.setSubSuspendType(reportDto.getSubSuspendType());
            stServiceReport.setSubSuspendTypeName(reportDto.getSubSuspendTypeName());
            stServiceReport.setWorkSuspendReason(reportDto.getWorkSuspendReason());
            stServiceReport.setConcernReason(reportDto.getConcernReason());
            stServiceReport.setEqSign(reportDto.getEqSign());
            stServiceReport.setReceiver(reportDto.getReceiver());
            stServiceReport.setReceiverPhone(reportDto.getReceiverPhone());
            stServiceReport.setReceiverMobile(reportDto.getReceiverMobile());
            stServiceReport.setReceiverEmail(reportDto.getReceiverEmail());
            updateServiceNotice(reportDto);

            // 服务报告信息插入主表st_report_info
            ReportInfo reportInfo = reportInfoMapper.selectStReportInfoByBatchType(reportDto.getId(), "1");
            if (null == reportInfo) {
                reportInfo = new ReportInfo();
                reportInfo.setServiceNo(stServiceReport.getServiceNo());
                reportInfo.setEnginnerId(stServiceReport.getEnginnerId());
                reportInfo.setPlanId(reportDto.getPlanId());
                reportInfo.setRelServiceNo(1L);
                reportInfo.setRelPlanId("st_service_report");
                reportInfo.setBatchType(stServiceReport.getId());
                reportInfo.setDelFlag("0");
                reportInfo.setNoticeId(reportDto.getNoticeId());
                reportInfo.setSyncFlag("0");
                reportInfo.setFseName(reportDto.getFseName());
                reportInfo.setServiceResult(stServiceReport.getServiceResult());
                reportInfo.setCreateTime(new Date());
                reportInfo.setCreateBy(stServiceReport.getEnginnerId() + "");
                reportInfoMapper.insertStReportInfo(reportInfo);


                // 关联日志
//                List<ServiceLog> serviceLogs = serviceLogMapper.selectServiceLogsList(stServiceReport.getServiceNo(), stServiceReport.getEnginnerId()); // 查询关联日志
                List<ServiceLog> serviceLogs = getNoFlagLogList(stServiceReport.getServiceNo(), stServiceReport.getEnginnerId());
                if (null != serviceLogs) {
                    for (ServiceLog serviceLog : serviceLogs) {
                        serviceLog.setReportId(reportInfo.getId().toString());
                        serviceLog.setUpdateTime(new Date());
                        serviceLogMapper.updateServiceLog(serviceLog);
                    }
                }
            } else {
                reportInfo.setUpdateTime(new Date());
                reportInfo.setUpdateBy(stServiceReport.getEnginnerId() + "");
                reportInfo.setServiceResult(stServiceReport.getServiceResult());
                reportInfoMapper.updateStReportInfo(reportInfo);
            }


            // 更新附件图片信息
            Annex annex = new Annex();
            annex.setRelationId(stServiceReport.getId().toString());
            annex.setTblName("st_service_report");
            annex.setUpdateTime(new Date());
            annexMapper.updateAnnexByHelpIdAndServiceNo(annex);

            // 更新备件信息
            reportPortMapper.updatePhoneReportPortByHelpIdAndServiceNo(stServiceReport.getId(), stServiceReport.getHelpId(), stServiceReport.getServiceNo());

            /////草稿保存更新结束/////////////////////////////////////////////
            //第一次费用保存结束

//detailServiceReportFee2
//            // 计算费用
//            // 只要数量/天/小时大于0才参与计算
//            if (stServiceReport.getManHours() >= 0) {
//                JSONObject response = ccService.GetServiceCharge(reportDto.getEnginnerId() + "", reportDto.getBu(), reportDto.getProv(), reportDto.getCity());
//                // 如果等于1有值，否则没有值
//                if ("1".equals(response.getString("status"))) {
//                    JSONObject jsonObject = response.getJSONArray("record").getJSONObject(0);
//                    double hourFee = jsonObject.getDouble("hour_fee");
//                    double basicFee = jsonObject.getDouble("basic_fee");
//                    double minHour = jsonObject.getDouble("min_hour");
//                    double partsTotallFee = reportPortMapper.selectReportPortsPrices(reportDto.getServiceNo(), reportDto.getHelpId(), "1");
//                    // 如果前台传过来的通过计算后和数据库中的不相等则重新计算，相等则不计算
//                    if ((reportDto.getChargeHours() >= 0 && (reportDto.getChargeHours() - minHour) != stServiceReport.getManHours()) || partsTotallFee != stServiceReport.getPartsTotallFee()) {
//                        // 显示字段1：Labor 人工——Quantity数量/Day天/Hour 小时 = 报告中的收费小时数-min_hour = 3-2 =1
//                        double newMinHout;
//                        // 显示字段2：Labor 人工——Rate 单价 = hour_fee = 640
//                        double newRate = hourFee;
//                        // 显示字段3：Labor 人工——Total 总计 = 1*640 =640
//                        double newTotal;
//                        // 显示字段4：Basic Price 基本费 = basic_fee = 1280
//                        double newBasicPrice = basicFee;
//                        // 显示字段5：Travel and Labor 旅途和人工费 = "Labor 人工——Total 总计"+"Basic Price 基本费" = 640+1280 = 1920
//                        double newTravelAndLabor;
//                        if (stServiceReport.getTravelStayPrice() > 0) {
//                            if (stServiceReport.getManHours() > 0) {
//                                newMinHout = stServiceReport.getManHours();
//                            } else {
//                                newMinHout = 0;
//                            }
//                            newRate = stServiceReport.getManRate();
//                            newTotal = newMinHout * newRate;
//                            newTravelAndLabor = newTotal + stServiceReport.getTravelStayPrice();
//                            newBasicPrice = 0;
//                        } else {
//                            newMinHout = (reportDto.getChargeHours() - minHour) < 0 ? 0 : (reportDto.getChargeHours() - minHour);
//                            newTotal = newMinHout * newRate;
//                            newTravelAndLabor = newTotal + newBasicPrice;
//                        }
//
//                        // 显示字段6：Total to be billed 总费用（含13%税）= 报告中的备件总费用+”Travel and Labor 旅途和人工费“ +“特殊费用” = 111+1920+0 = 2031
//                        double newTotalToBeBilled = partsTotallFee + newTravelAndLabor + (stServiceReport.getEspeciallyFee() == null ? 0 : stServiceReport.getEspeciallyFee());
//                        stServiceReport.setMinHour(minHour);
//                        stServiceReport.setManHours((int) newMinHout);
//                        stServiceReport.setBasicFee(newBasicPrice);
//                        stServiceReport.setManRate(newRate);
//                        stServiceReport.setTotalPrice(newTotal);
//                        stServiceReport.setTotalBilled(newTotalToBeBilled);
//                        stServiceReport.setManTotal(newTravelAndLabor);
//                        stServiceReport.setPartsTotallFee(partsTotallFee);
//                    }
//                }
//                else
//                    {
//                    double partsTotallFee = reportPortMapper.selectReportPortsPrices(reportDto.getServiceNo(), reportDto.getHelpId(), "1");
//                    // 只要他俩不相等说明修改过
//                    if ((reportDto.getChargeHours() >= 0 && ((reportDto.getChargeHours() - stServiceReport.getManHours()) > 0 || (reportDto.getChargeHours() - stServiceReport.getManHours()) < 0)) || partsTotallFee != stServiceReport.getPartsTotallFee()) {
//                        double hourFee = stServiceReport.getManRate();
//                        double basicFee = stServiceReport.getBasicFee();
//                        double minHour = reportDto.getChargeHours();
//
//                        // 显示字段1：Labor 人工——Quantity数量/Day天/Hour 小时 = 报告中的收费小时数-min_hour = 3-2 =1
//                        double newMinHout;
//                        // 显示字段2：Labor 人工——Rate 单价 = hour_fee = 640
//                        double newRate = hourFee <= 0 ? 0 : hourFee;
//                        // 显示字段3：Labor 人工——Total 总计 = 1*640 =640
//                        double newTotal;
//                        // 显示字段4：Basic Price 基本费 = basic_fee = 1280
//                        double newBasicPrice = basicFee;
//                        // 显示字段5：Travel and Labor 旅途和人工费 = "Labor 人工——Total 总计"+"Basic Price 基本费" = 640+1280 = 1920
//                        double newTravelAndLabor;
//
//                        if (stServiceReport.getTravelStayPrice() > 0) {
//                            if (stServiceReport.getManHours() > 0) {
//                                newMinHout = stServiceReport.getManHours();
//                            } else {
//                                newMinHout = 0;
//                            }
//                            newTotal = newMinHout * newRate;
//                            newTravelAndLabor = newTotal + stServiceReport.getTravelStayPrice();
//                        } else {
//                            newMinHout = minHour;
//                            newTotal = newMinHout * newRate;
//                            newTravelAndLabor = newTotal + newBasicPrice;
//                        }
//
//                        // 显示字段6：Total to be billed 总费用（含13%税）= 报告中的备件总费用+”Travel and Labor 旅途和人工费“ +“特殊费用” = 111+1920+0 = 2031
//                        double newTotalToBeBilled = partsTotallFee + newTravelAndLabor + (stServiceReport.getEspeciallyFee() == null ? 0 : stServiceReport.getEspeciallyFee());
//
//                        stServiceReport.setManHours((int) newMinHout);
//                        stServiceReport.setBasicFee(newBasicPrice);
//                        stServiceReport.setManRate(newRate);
//                        stServiceReport.setTotalPrice(newTotal);
//                        stServiceReport.setTotalBilled(newTotalToBeBilled);
//                        stServiceReport.setManTotal(newTravelAndLabor);
//                        stServiceReport.setPartsTotallFee(partsTotallFee);
//                    }
//                }
//            }

            double partsTotallFee = reportPortMapper.selectReportPortsPrices(reportDto.getServiceNo(), reportDto.getHelpId(), "1");
            StCost cost = addCCFree(reportDto);
            if (cost != null) {
                if ("0".equals(cost.getFeeBalanceType())) {
//                    stServiceReport.setManHours(0);// 收费小时数
//                    stServiceReport.setManRate(0.0);//单价
//                    stServiceReport.setTotalPrice(0.0);//人工费
//                    stServiceReport.setTravelStayPrice(0.0);
//                    double mantotal = 0.0;
//                    stServiceReport.setManTotal(mantotal);//人工旅途费


                    stServiceReport.setPartsTotallFee(partsTotallFee);//备件费用
                    stServiceReport.setTotalBilled(stServiceReport.getManTotal() + partsTotallFee);///报告总费用
                }
                if ("1".equals(cost.getFeeBalanceType())) {
                    double basefeeValue = 0.0;
                    if (reportDto.getChargeHours() > 0) {
                        basefeeValue = cost.getBasicFee();
                        stServiceReport.setBasicFee(basefeeValue);// 基本费用
                    } else {
                        basefeeValue = 0;
                        stServiceReport.setBasicFee(basefeeValue);// 基本费用
                    }
                    double feeHour = reportDto.getChargeHours() - cost.getMinHour();
                    if (feeHour < 0) {
                        feeHour = 0;
                    }
                    stServiceReport.setManHours(feeHour);// 收费小时数
                    stServiceReport.setManRate(cost.getHourFee());//单价
                    stServiceReport.setTotalPrice(feeHour * cost.getHourFee());//人工费

                    double mantotal = (stServiceReport.getManHours() * stServiceReport.getManRate()) + basefeeValue;
                    stServiceReport.setManTotal(mantotal);//人工旅途费

                    stServiceReport.setPartsTotallFee(partsTotallFee);//备件费用
                    stServiceReport.setTotalBilled(mantotal + partsTotallFee);///报告总费用
                }

                if ("2".equals(cost.getFeeBalanceType())) {
                    double basefee = cost.getBasicFee();
                    if (basefee > 0) {
                        double basefeeValue = 0.0;
                        if (reportDto.getChargeHours() > 0) {
                            basefeeValue = cost.getBasicFee();
                            stServiceReport.setBasicFee(basefeeValue);// 基本费用
                        } else {
                            basefeeValue = 0;
                            stServiceReport.setBasicFee(basefeeValue);// 基本费用
                        }
                        double feeHour = reportDto.getChargeHours() - cost.getMinHour();
                        if (feeHour < 0) {
                            feeHour = 0;
                        }
                        stServiceReport.setManHours(feeHour);// 收费小时数
                        stServiceReport.setManRate(cost.getHourFee());//单价
                        stServiceReport.setTotalPrice(feeHour * cost.getHourFee());//人工费
                        double mantotal = (stServiceReport.getManHours() * stServiceReport.getManRate()) + basefeeValue;
                        stServiceReport.setManTotal(mantotal);//人工旅途费

                        stServiceReport.setPartsTotallFee(partsTotallFee);//备件费用
                        stServiceReport.setEspeciallyFee(cost.getEspeciallyFee());
                        stServiceReport.setTotalBilled(mantotal + partsTotallFee + cost.getEspeciallyFee());///报告总费用

                    } else {
                        //detailServiceReportFee2
//                        stServiceReport.setManHours(0);// 收费小时数
//                        stServiceReport.setManRate(0.0);//单价
//                        stServiceReport.setTotalPrice(0.0);//人工费
//                        stServiceReport.setTravelStayPrice(0.0);
//                        double mantotal = 0.0;
//                        stServiceReport.setManTotal(mantotal);//人工旅途费

                        stServiceReport.setPartsTotallFee(partsTotallFee);//备件费用
                        stServiceReport.setEspeciallyFee(cost.getEspeciallyFee());
                        stServiceReport.setTotalBilled(stServiceReport.getManTotal() + partsTotallFee + cost.getEspeciallyFee());///报告总费用
                    }
                }
            }


            // 更新服务报告数据
            stServiceReportMapper.updateStServiceReport(stServiceReport);
            //更新CC备件信息
            deleteCCReportPart(stServiceReport);
            reportInfo.setReportInfo(stServiceReport);
            return new ResponseWithData<>().success(reportInfo).code(200);
        }
    }

    private void updateServiceNotice(ServiceReportDto reportDto) {
        ServiceNotice serviceNotice = new ServiceNotice();
        serviceNotice.setId(reportDto.getNoticeId());
        serviceNotice.setContact(reportDto.getReceiver());
        serviceNotice.setTelephone(reportDto.getReceiverPhone());
        serviceNotice.setMobile(reportDto.getReceiverMobile());
        serviceNotice.setEmail(reportDto.getReceiverEmail());
        serviceNoticeMapper.updateServiceNotice(serviceNotice);
    }
//更新cca

    /***
     * 保存草稿前获取cc基本费用信息
     * @param reportDto
     * @return
     */
    private StCost addCCFree(ServiceReportDto reportDto) {

        // 计算费用**************  开始  -从cc取值
        StCost cost = null;
        StServiceReport serviceReport = stServiceReportMapper.selectStServiceReportByServiceNoAndHelpId(reportDto.getServiceNo(), reportDto.getHelpId());
        //特殊费用
        JSONObject checkServiceEspecial = ccService.CheckServiceEspecial(reportDto.getServiceNo());
        //基础费用
        JSONObject response = ccService.GetServiceCharge(reportDto.getEnginnerId() + "", reportDto.getBu(), reportDto.getProv(), reportDto.getCity());

        //第一次费用保存
        JSONObject fistcheck = (JSONObject) checkServiceEspecial.getJSONArray("record").get(0);
        StCost stCost = new StCost();
        stCost.setFeeBalanceType(fistcheck.getString("FeeBalanceType"));
        if (fistcheck.getString("EspeciallyFee") == null) {
            stCost.setEspeciallyFee(0);
        } else {
            stCost.setEspeciallyFee(new Double(fistcheck.getString("EspeciallyFee")));
        }
        if (fistcheck.getString("EspeFeeDesc") == null) {
            stCost.setEspeFeeDesc("");
        } else {
            stCost.setEspeFeeDesc(fistcheck.getString("EspeFeeDesc"));
        }

        JSONArray ccFeeArrayFirst = response.getJSONArray("record");
        if (!ObjectUtils.isEmpty(ccFeeArrayFirst)) {
            JSONObject fisetccFee = (JSONObject) ccFeeArrayFirst.get(0);
            stCost.setBasicFee(new Double(fisetccFee.getString("basic_fee")));
            stCost.setHourFee(new Double(fisetccFee.getString("hour_fee")));
            stCost.setMinHour(new Double(fisetccFee.getString("min_hour")));
        }
        stCost.setServiceNo(reportDto.getServiceNo());
        stCost.setFse(reportDto.getEnginnerId() + "");
        stCost.setHelpId(reportDto.getHelpId());
        List<StCost> stCostList = stCostMapper.selectStCostList(stCost);
        if (stCostList.size() < 1) {
            stCostMapper.insertStCost(stCost);
            cost = stCost;
        } else {
            cost = stCostList.get(0);
        }
        return cost;
    }


    private void deleteCCReportPart(StServiceReport serviceReport) {
        List<StReportPort> portList = reportPortMapper.selectStReportPortListByServiceNoAndHelpIdAndPortType(serviceReport.getServiceNo(), serviceReport.getHelpId(), null);
        for (StReportPort stReportPort : portList) {
            ccService.deleteCCParts(stReportPort.getPid());
        }
    }

    public static List<StReportPort> removeDupliById(List<StReportPort> persons) {
        Set<StReportPort> personSet = new TreeSet<>((o1, o2) -> o1.getPid().compareTo(o2.getPid()));
        personSet.addAll(persons);
        return new ArrayList<>(personSet);
    }

    /**
     * 提交服务报告
     *
     * @param id         服务报告主键ID
     * @param enginnerId 提交的工程师ID
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/10 2:49 下午
     */
    @Override
    public ResponseWithData<?> submitServiceReport(Long id, Long enginnerId) {
        if (null == id) {
            return new ResponseWithData<>().error().msg("id cannot be empty");
        }
        if (null == enginnerId) {
            return new ResponseWithData<>().error().msg("enginnerId cannot be empty");
        }

        // 查寻服务报告基本信息
        StServiceReport stServiceReport = stServiceReportMapper.selectStServiceReportById(id);

        ReportInfo reportInfo = reportInfoMapper.selectStReportInfoByBatchType(id, "1");

        // 判断非本人提交报告
        if ("1".equals(reportInfo.getSyncFlag())) {

        } else {
            if (!(enginnerId + "").equals(reportInfo.getEnginnerId() + "")) {
                String name = reportInfo.getFseName();
                return new ResponseWithData<>().error().msg("你不能提交" + name + "的报告, 如需提交请联系" + name);
            }
        }

        if (null == stServiceReport || null == reportInfo) {
            return new ResponseWithData<>().error().msg("服务报告不存在");
        }
        if ("1".equals(reportInfo.getSyncFlag())) {
            return new ResponseWithData<>().error().msg("此服务报告已提交过");
        }
        // 验证是否存在已完成的报告（服务报告或电话解决报告）
        List<ReportInfo> datas = reportInfoMapper.selectSubmitFinishStReportInfoByServiceNo(reportInfo.getId(), reportInfo.getServiceNo());
        if (StringUtils.isNotEmpty(datas)) {
            return new ResponseWithData<>().error("已存在已完成报告");
        }
        // add by wlf 20200520 存在未绑定日志时不可提交已完成报告
        if (stServiceReport.getServiceResult().equals("1")) { //1已完成,2未完成
            // 校验日志
//            ServiceNotice serviceNotice = serviceNoticeMapper.selectServiceNoticeByServiceNo(reportInfo.getServiceNo());
            ServiceDetails serviceDetails = new ServiceDetails();
            serviceDetails.setServiceNo(reportInfo.getServiceNo());
            serviceDetails.setFseId(enginnerId + "");
            List<ServiceDetails> serviceDetailsList = serviceDetailsMapper.selectServiceDetailsList(serviceDetails);
            List<ServiceLog> noFlagLogs = serviceLogMapper.selectServiceLogsListNoflags(reportInfo.getServiceNo(), null); //未关联的日志
            // serviceRole：1现场服务；2：实习
            if (null != serviceDetailsList && serviceDetailsList.size() > 0 && serviceDetailsList.get(0).getServiceRole().equals("2")) {
                return new ResponseWithData<>().error().msg("您此次的服务角色是实习，不可提交服务报告");
            }

            if (noFlagLogs != null && noFlagLogs.size() > 0) {
                HashMap<String, String> hashMapName = new HashMap();
                for (ServiceLog serviceLog : noFlagLogs) {
                    if (!hashMapName.containsKey(serviceLog.getFseName())) {
                        hashMapName.put(serviceLog.getFseName(), serviceLog.getFseName());
                    }
                }
                StringBuffer nameList = new StringBuffer();
                for (String name : hashMapName.values()) {
                    nameList.append(name + ",");
                }
                String fseName = nameList.deleteCharAt(nameList.length() - 1).toString();
                return new ResponseWithData<>().error().msg(fseName + "有未关联报告的日志，不可提交已完成的服务报告");
            }

            // 20200528 校验是否存在草稿状态的报告
            ReportInfo info = new ReportInfo();
            info.setServiceNo(reportInfo.getServiceNo());
            // info.setPlanId(reportInfo.getPlanId());
            info.setSyncFlag("0");
            //  info.setRelServiceNo(6L); //电话解决报告
            info.setDelFlag("0");
            List<ReportInfo> plist = reportInfoMapper.selectStReportInfoList(info);
            if (!ObjectUtils.isEmpty(plist)) {
                //不能有任何草稿的报告
                int i = 0;
                for (ReportInfo reportInfo1 : plist) {
                    i++;
                    if (i >= 2) {
                        return new ResponseWithData<>().error().msg("存在未提交的报告，不可提交已完成服务报告");
                    }
                    if (StringUtils.equals("1", reportInfo1.getRelServiceNo().toString())) {
                        if (!StringUtils.equals(id.toString(), reportInfo1.getBatchType().toString())) {
                            return new ResponseWithData<>().error().msg("存在未提交的服务报告，不可提交已完成服务报告");
                        }
                    } else {
                        return new ResponseWithData<>().error().msg("存在未提交的报告，不可提交已完成服务报告");
                    }
                }
            }

            //    只能有一个已完成电话/服务报告

//            List<ReportInfo> reportInfoList = reportInfoMapper.selectReportFinishByServiceNo(reportInfo.getServiceNo());
//            if (!ObjectUtils.isEmpty(reportInfoList) && reportInfoList.size() > 1) {
//                return new ResponseWithData<>().error().msg("只能有一个已完成报告");
//            }
        }

//        if (stServiceReport.getServiceResult().equals("2")) {
//            ReportInfo info = new ReportInfo();
//            info.setServiceNo(reportInfo.getServiceNo());
//            info.setPlanId(reportInfo.getPlanId());
//            info.setSyncFlag("1");
//            //  info.setRelServiceNo(6L); //电话解决报告
//            info.setDelFlag("0");
//            List<ReportInfo> plist = reportInfoMapper.selectStReportInfoList(info);
//            if (!ObjectUtils.isEmpty(plist)) {
//                return new ResponseWithData<>().error().msg("存在已提交的报告，不可提交服务报告");
//            }
//        }


        deleteCCReportPart(stServiceReport);
        Map<String, Object> params = new HashMap<>();
        // 唯一主键
        params.put("report_guid", reportInfo.getId() + "");

        // Service号
        params.put("service_no", reportInfo.getServiceNo());
        // 提交的工程师ID
        params.put("enginner_id", enginnerId + "");
        // 接待人
        params.put("receiver", stServiceReport.getReceiver());
        // 接待人手机
        params.put("receiver_mobile", stServiceReport.getReceiverMobile());
        // 接待人邮箱
        params.put("receiver_email", stServiceReport.getReceiverEmail());
        // Failure类型1
        params.put("failure_type1", stServiceReport.getFailureType1() + "");
        // Failure类型2
        params.put("failure_type2", stServiceReport.getFailureType2() + "");
        // Failure类型3
        params.put("failure_type3", stServiceReport.getFailureType3() + "");
        // 响应慢的原因
        params.put("low_reason", stServiceReport.getLowReason());
        // 响应慢的原因（其他备注）
        params.put("low_other_reason", stServiceReport.getLowOtherReason());
        // 故障
        params.put("problem", stServiceReport.getProblem());
        // 工作过程
        if (StringUtils.isNotEmpty(stServiceReport.getActionTaken())) {
            params.put("action_taken", HtmlUtils.htmlEscape(stServiceReport.getActionTaken()));
        } else {
            params.put("action_taken", "");
        }

        // 服务类型
        String st = stServiceReport.getServiceType();
        String stValue = "";
        if (st.equals("安装")) {
            stValue = "1,0,0,0,0";
        } else if (st.equals("保内")) {
            stValue = "0,1,0,0,0";
        } else if (st.equals("保外")) {
            stValue = "0,0,1,0,0";
        } else if (st.equals("服务合同")) {
            stValue = "0,0,0,1,0";
        } else { //其他SystemApiServiceImpl.java
            stValue = "0,0,0,0,1";
        }
        params.put("service_type", StringUtils.isEmpty(stValue) ? "" : stValue);

        // 接收任务时间
        params.put("order_received_date", DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stServiceReport.getOrderReceivedDate()));
        // 出发时间
        params.put("start_travel_date", DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stServiceReport.getStartTravelDate()));
        // 达到现场时间
        params.put("on_site_data", DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stServiceReport.getOnSiteData()));
        // 总旅途小时数
        params.put("travel_time", stServiceReport.getTravelTime() + "");
        // 工作开始时间
        params.put("start_working_time", DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stServiceReport.getStartWorkingTime()));
        // 工作结束时间
        params.put("end_working_time", DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stServiceReport.getEndWorkingTime()));
        // 总工作小时数
        params.put("total_working_hours", stServiceReport.getTotalWorkingHours() + "");
        // 收费小时数
        params.put("charge_hours", stServiceReport.getChargeHours() + "");
        // 应用支持小时数
        params.put("app_support_hours", stServiceReport.getAppSupportHours() + "");
        // 等待客户小时数
        params.put("waiting_hours", stServiceReport.getWaitingHours() + "");
        // 结果
        params.put("results", stServiceReport.getResults());
        // 工程师建议
        params.put("engineers_advis", stServiceReport.getEngineersAdvis());
        // 服务结果
        params.put("service_result", stServiceReport.getServiceResult());
        // 英文故障描述
        params.put("en_problem_description", stServiceReport.getEnProblemDescription());
        // 培训类型
        params.put("TrainType", stServiceReport.getTrainType());
        // 参加培训人数
        params.put("TrainNum", stServiceReport.getTrainNum());
        // 参加人员姓名
        params.put("TrainFSE", stServiceReport.getTrainFse());
        // 参加人员ID
        params.put("TrainFSECode", stServiceReport.getTrainFseCode());
        // 培训小时数
        params.put("TrainHour", stServiceReport.getTrainHour() + "");
        // 培训开始时间
        params.put("TrainStart", DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stServiceReport.getTrainStart()));
        // 培训结束时间
        params.put("TrainEnd", DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stServiceReport.getTrainEnd()));
        // 培训地点
        params.put("TrainPlace", stServiceReport.getTrainPlace());
        // 其他培训地点
        params.put("OtherPlace", stServiceReport.getOtherPlace());
        // 培训对象
        params.put("TrainObject", stServiceReport.getTrainObject());
        // 培训内容（客户）
        params.put("CusLevel", stServiceReport.getCusLevel());
        // 培训级别
        params.put("FSELevel", stServiceReport.getFseLevel());
        // 旅途时间
        params.put("JourHour", stServiceReport.getJourHour() + "");
        // AE工程师
        params.put("AEFse", stServiceReport.getAeFse());
        // 预计下次到现场时间
        params.put("expected_next_time", DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stServiceReport.getExpectedNextTime()));
        // 中断类型
        params.put("suspend_type", stServiceReport.getSuspendType() + "");
        // 中断子类型
        params.put("suspend_subtype", stServiceReport.getSubSuspendType() + "");
        // 工作中断原因
        params.put("work_suspend_reason", stServiceReport.getWorkSuspendReason());
        // 关注原因
        params.put("concern_reason", stServiceReport.getConcernReason());
        // MD问题1
        params.put("ques_one", stServiceReport.getQuesOne());
        // MD问题2
        params.put("ques_two", stServiceReport.getQuesTwo());
        // MD问题3
        params.put("ques_three", stServiceReport.getQuesThree());
        // MD问题4
        params.put("ques_four", stServiceReport.getQuesFour());
        // MD问题5
        params.put("ques_five", stServiceReport.getQuesFive());
        // MD问题5.1
        params.put("ques_fiveone", stServiceReport.getQuesFiveone());
        // 基本费
        params.put("BasicFee", stServiceReport.getBasicFee() + "");
        // 人工费
        params.put("ManRate", stServiceReport.getManRate() + "");
        // 人工小时
        params.put("ManHours", stServiceReport.getManHours() + "");
        // 人工总费用
        params.put("ManTotal", stServiceReport.getTotalPrice() + "");//对应人工总费用
        //Travel and Hotel 旅途和住宿费
        params.put("TravelHotel", stServiceReport.getTravelStayPrice());
        //Travel and Labor 旅途和人工费
        params.put("TravelLabor", stServiceReport.getManTotal());//旅途和人工费
        // 备件总费用
        params.put("PartsTotallFee", stServiceReport.getPartsTotallFee() + "");
        // 报告总费用
        params.put("TotalBilled", stServiceReport.getTotalBilled() + "");
        params.put("EspeciallyFee", ObjectUtils.isEmpty(stServiceReport.getEspeciallyFee()) ? "0.0" : stServiceReport.getEspeciallyFee());
        //        params.put("TravelHotel", "1");
//        params.put("TravelLabor", "2");
        params.put("EqSign", "3");

        // 备件信息
        List<StReportPort> reportPorts = reportPortMapper.selectStReportPortListByServiceNoAndHelpIdAndPortType(stServiceReport.getServiceNo(), stServiceReport.getHelpId(), "1");

        //   List<StReportPort> reportPorts = reportPortMapper.selectStReportPortListByReportIdAndPortType(stServiceReport.getId(), "1");
        //获取已提交的报告备件
        // List<StReportPort> reportPortsSubmited = reportPortMapper.getSubmitServiceAndPhoneReportPorts(stServiceReport.getServiceNo());
//        if (null != reportPorts) {
//            if (null != reportPortsSubmited) {
//
//                reportPorts.addAll(reportPortsSubmited);
//            }
//        } else {
//            reportPorts = reportPortsSubmited;
//        }
        if (null != reportPorts) {
            reportPorts = removeDupliById(reportPorts);
            List<Map<String, Object>> reportPortParams = new ArrayList<>();
            for (StReportPort reportPort : reportPorts) {
                Map<String, Object> reportPortParam = new HashMap<>();
                // 备件号
                reportPortParam.put("part_number", reportPort.getPartNumber());
                // 借贷单号
                reportPortParam.put("loan_number", reportPort.getLoanNumber());
                // 备件序列号
                if (StringUtils.isEmpty(reportPort.getPartSerialNumber())) {
                    reportPortParam.put("part_serial_number", "");
                } else {
                    reportPortParam.put("part_serial_number", reportPort.getPartSerialNumber());
                }

                // 备件名称
                reportPortParam.put("part_name", reportPort.getPartName());
                // QTY数量  备件数量
                reportPortParam.put("qty_count", reportPort.getQtyCount());
                // Price单价
                reportPortParam.put("price", reportPort.getPrice());
                // Price总价
                reportPortParam.put("totalprice", reportPort.getTotalprice());
                // 更换类型 备件类型
                reportPortParam.put("part_type", reportPort.getPartType() == null ? "" : reportPort.getPartType());
                // 备件收货地址
                reportPortParam.put("Parts_Address", StringUtils.isEmpty(reportPort.getAddress()) ? "" : reportPort.getAddress());
                // 备注
                reportPortParam.put("remark", StringUtils.isEmpty(reportPort.getRemark()) ? "" : reportPort.getRemark());
                // 坏件序列号
                reportPortParam.put("Damage_serial_number", StringUtils.isEmpty(reportPort.getDamageSerialNumber()) ? "" : reportPort.getDamageSerialNumber());

                // 坏件图片
                List<Annex> annexes = annexMapper.selectAnnexListByHelpIdAndServiceNo(reportPort.getServiceNo(), reportPort.getAnnexHelpId());
                if (null != annexes) {
                    String path = "";
                    for (Annex annex : annexes) {
                        path =
                                //global.getPicUrl() +
                                annex.getFilePath();
                    }
                    reportPortParam.put("Damage_pic", path);
                } else {
                    reportPortParam.put("Damage_pic", "");
                }

                // 坏件是否还库
                reportPortParam.put("IsOutWarranty", StringUtils.isEmpty(reportPort.getIsOutWarranty()) ? "" : reportPort.getIsOutWarranty());
                // 备件状态变更说明
                reportPortParam.put("StatusChange", StringUtils.isEmpty(reportPort.getStatusChange()) ? "" : reportPort.getStatusChange());
                // 备件状态变更备注
                reportPortParam.put("ChangeRemark", StringUtils.isEmpty(reportPort.getChangeRemark()) ? "" : reportPort.getChangeRemark());
                // 备件编号
                reportPortParam.put("PID", reportPort.getPid());

                reportPortParams.add(reportPortParam);
            }
            params.put("part_data", JSON.toJSONString(reportPortParams));
        } else {
            params.put("part_data", "[]");
        }

        // 图片信息
        List<Annex> annexes = annexMapper.selectAnnexByTblNameAndRelationId("st_service_report", stServiceReport.getId().toString());
        if (null != annexes) {
            List<Map<String, Object>> annexParams = new ArrayList<>();
            for (Annex annex : annexes) {
                JSONObject map = new JSONObject();
                map.put("Pic_Path",
                        //global.getPicUrl() +
                        annex.getFilePath());
                if (StringUtils.isEmpty(annex.getFileDescription())) {
                    map.put("Pic_Remark", "");
                } else {
                    map.put("Pic_Remark", annex.getFileDescription());
                }

                map.put("CREATE_TIME", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, annex.getCreateTime()));
                annexParams.add(map);
            }
            params.put("pic_list", annexParams);


        } else {
            params.put("pic_list", "[]");
        }

        //临时方案，根据服务号查询当前服务单的接待人，接待人手机 ，接待人邮箱
        ServiceNotice serviceNotice = serviceNoticeMapper.selectServiceNoticeByServiceNo(reportInfo.getServiceNo());
        if (serviceNotice != null) {
            params.put("receiver", serviceNotice.getContact());//联系人
            params.put("receiver_mobile", serviceNotice.getMobile());//手机
            params.put("receiver_email", serviceNotice.getEmail());//邮箱
            params.put("receiver_telephone", serviceNotice.getTelephone());//电话
        }
        // 请求CC接口 提交电话解决报告
        String response = ccService.serviceSubmithandle(params);
        /** 如果调用接口异常直接返回 */
        if (null == response) {
            return new ResponseWithData().error().msg("提交服务报告失败 调用CC端提交服务报告接口发生异常").code(202);
        }

        JSONObject jsonObject = JSONObject.parseObject(response);
        String status = jsonObject.getString("status");
        if ("1".equals(status)) {
            String rptNo = "";
            try {
                JSONArray record = jsonObject.getJSONArray("record");
                if (record != null && record.size() > 0) {
                    rptNo = record.getJSONObject(0).getString("rpt_no");
                }
            } catch (Exception e) {
                log.error("程序异常", e.getMessage());
            }

            // 提交成功 ，更新同步状态
            ReportInfo info = new ReportInfo();
            info.setId(reportInfo.getId());
            info.setSyncFlag("1");
            info.setSyncTime(new Date());
            info.setReportNo(rptNo);
            reportInfoMapper.updateStReportInfo(info);

            //签离状态 工单状态 为已完成
            ServiceDetails serviceDetails = new ServiceDetails();
            serviceDetails.setServiceNo(reportInfo.getServiceNo());
            serviceDetails.setFseId(enginnerId + "");
            List<ServiceDetails> serviceDetailsList = serviceDetailsMapper.selectServiceDetailsList(serviceDetails);
            ServiceDetails serviceDetailsUpdate = serviceDetailsList.get(0);
            if ("1".equals(reportInfo.getServiceResult())) {
                if ("3".equals(serviceDetailsUpdate.getState() + "")) {
                    serviceDetailsUpdate.setState(new Long(4));
                    serviceDetailsUpdate.setUpdateTime(new Date());
                    serviceDetailsMapper.updateServiceDetails(serviceDetailsUpdate);
                }
            }

            return new ResponseWithData().success().msg("提交服务报告成功").code(200);
        } else if ("2".equals(status)) {
            String message = jsonObject.getString("message");
            return new ResponseWithData().error().msg(message).code(201);
        } else {
            return new ResponseWithData().error().msg("提交服务报告失败 调用CC端提交服务报告接口发生异常").code(201);
        }
    }

    @Override
    public ResponseWithData<?> getServiceRportSignature(Signatures signatures) throws Exception {

        if (StringUtils.isNotEmpty(signatures.getServiceNo())) {
            // 查询已经完成的现场服务报告和验收报告
            List<ReportInfo> reportInfoSignature = reportInfoMapper.getReportInfoSignature(signatures.getServiceNo());
            if (reportInfoSignature != null && reportInfoSignature.size() > 0) {
                String imgName = UUID.randomUUID().toString().replace("-", "") + ".jpg";
                // 判断是否需要发送邮件
                String email = "";
                if ("1".equals(signatures.getIsSendEmail())) {
//                    ServiceNotice serviceNotice = serviceNoticeMapper.selectServiceNoticeById(signatures.getServiceNoticeId());
//                    if(serviceNotice!=null && StringUtils.isNotEmpty(serviceNotice.getEmail())){
//                        email = email + "," + serviceNotice.getEmail();
//                    }
                    email = signatures.getEmailAddress().replaceAll(";", ",");
                }

                for (ReportInfo reportInfo : reportInfoSignature) {
                    // 现场服务报告
                    if (reportInfo.getRelServiceNo() == 1) {
                        this.signPicAndSendEmailSubmithandle(signatures.getServiceNo(), reportInfo.getId() + "", signatures.getEnginnerId() + "", imgName, signatures.getB().split(",")[1], signatures.getIsSendEmail(), email);
//                        this.signPicAndSendEmailSubmithandle(signatures.getServiceNo(), "123", signatures.getEnginnerId()+"", imgName, signatures.getB().split(",")[1], signatures.getIsSendEmail(), email);
                    }
                    // 验收报告
                    if (reportInfo.getRelServiceNo() == 4) {
                        this.inssignPicAndSendEmailSubmit(signatures.getServiceNo(), reportInfo.getId() + "", signatures.getEnginnerId() + "", imgName, signatures.getB().split(",")[1], signatures.getIsSendEmail(), email);
//                        this.inssignPicAndSendEmailSubmit(signatures.getServiceNo(), "234", signatures.getEnginnerId()+"", imgName, signatures.getB().split(",")[1], signatures.getIsSendEmail(), email);
                    }
                }

                return new ResponseWithData<>().success().msg("签名成功").code(200);

            }
        }

        return new ResponseWithData<>().error().msg("签名失败").code(201);

    }

    /**
     * 查看服务报告费用详情
     *
     * @param
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/10 11:03 上午
     */
    @Override
    public ResponseWithData<?> detailServiceReportFee(String serviceNo, Long enginnerId, String helpId, String
            bu, String prov, String city) {
        StServiceReport serviceReport = stServiceReportMapper.selectStServiceReportByServiceNoAndHelpId(serviceNo, helpId);
        //特殊费用
        JSONObject checkServiceEspecial = ccService.CheckServiceEspecial(serviceNo);
        //基础费用
        JSONObject response = ccService.GetServiceCharge(enginnerId + "", bu, prov, city);

        //第一次费用保存
        JSONObject fistcheck = (JSONObject) checkServiceEspecial.getJSONArray("record").get(0);
        StCost stCost = new StCost();
        stCost.setFeeBalanceType(fistcheck.getString("FeeBalanceType"));
        if (fistcheck.getString("EspeciallyFee") == null) {
            stCost.setEspeciallyFee(0);
        } else {
            stCost.setEspeciallyFee(new Double(fistcheck.getString("EspeciallyFee")));
        }
        if (fistcheck.getString("EspeFeeDesc") == null) {
            stCost.setEspeFeeDesc("");
        } else {
            stCost.setEspeFeeDesc(fistcheck.getString("EspeFeeDesc"));
        }


        JSONArray ccFeeArrayFirst = response.getJSONArray("record");
        if (!ObjectUtils.isEmpty(ccFeeArrayFirst)) {
            JSONObject fisetccFee = (JSONObject) ccFeeArrayFirst.get(0);
            stCost.setBasicFee(new Double(fisetccFee.getString("basic_fee")));
            stCost.setHourFee(new Double(fisetccFee.getString("hour_fee")));
            stCost.setMinHour(new Double(fisetccFee.getString("min_hour")));
        }
        stCost.setServiceNo(serviceNo);
        stCost.setFse(enginnerId + "");

        List<StCost> stCostList = stCostMapper.selectStCostList(stCost);
        if (stCostList.size() == 0) {
            stCostMapper.insertStCost(stCost);
        }
        //第一次费用保存结束


        Map<String, Object> data = new HashMap<>();
//        data.put("checkServiceEspecial", checkServiceEspecial);
//        data.put("cc", response);
        double partsTotallFee = reportPortMapper.selectReportPortsPrices(serviceNo, helpId, "1");
        if (null != serviceReport) {
            //已保存的报告
            data.put("manHours", serviceReport.getManHours());//人工小时
            data.put("manRate", serviceReport.getManRate());//人工费用
            data.put("totalPrice", serviceReport.getTotalPrice());//人工总费用
            data.put("travelStayPrice", serviceReport.getTravelStayPrice());//旅途住宿费用
            data.put("manTotal", serviceReport.getManTotal());//人工和旅途住宿费总费用
            data.put("especiallyFee", serviceReport.getEspeciallyFee());//特殊费用
            data.put("partsTotallFee", partsTotallFee);//备件费用
            data.put("totalBilled", serviceReport.getTotalBilled());//报告总费用
            data.put("feeBalanceType", serviceReport.getFeeBalanceType());
            data.put("chargeHours", serviceReport.getChargeHours());//收费小时数
            data.put("basicFee", serviceReport.getBasicFee());//基本费用
            data.put("min_hour", serviceReport.getMinHour());

            data.put("checkState", serviceReport.getMinHour());
            data.put("hour_fee", serviceReport.getMinHour());
            data.put("ccState", serviceReport.getMinHour());
            data.put("ccLength", serviceReport.getMinHour());

        } else {
            //没有保存的报告
            data.put("manHours", 0);
            data.put("manRate", 0);
            data.put("totalPrice", 0);

            data.put("travelStayPrice", 0);
            data.put("manTotal", 0);

            data.put("especiallyFee", 0);
            data.put("partsTotallFee", partsTotallFee);
            data.put("totalBilled", 0);

            data.put("chargeHours", 0);
            //   data.put("basicFee", 0);//基本费用
            data.put("basic_fee", 0);
            data.put("hour_fee", 0);
            data.put("min_hour", 0);
            data.put("checkState", 1);
            data.put("ccState", 1);
            data.put("ccLength", 0);
            data.put("feeBalanceType", "0");

//            if (StringUtils.equals("0.00", data.get("totalBilled").toString()) || StringUtils.equals("0", data.get("totalBilled").toString())) {
//                JSONObject check = (JSONObject) checkServiceEspecial.getJSONArray("record").get(0);
//                data.put("feeBalanceType", check.getString("FeeBalanceType"));
//                data.put("especiallyFee", check.getString("EspeciallyFee"));
//                data.put("checkState", checkServiceEspecial.getString("status"));
//                JSONArray ccFeeArray = response.getJSONArray("record");
//                if (!ObjectUtils.isEmpty(ccFeeArray)) {
//                    JSONObject ccFee = (JSONObject) ccFeeArray
//                            .get(0);
//                    data.put("basic_fee", ccFee.getString("basic_fee"));
//                    data.put("hour_fee", ccFee.getString("hour_fee"));
//                    data.put("min_hour", ccFee.getString("min_hour"));
//                    data.put("ccState", response.getString("status"));
//                    data.put("ccLength", ccFeeArray.size());
//                }
//
//            }
        }


        return new ResponseWithData<>().success(data).code(200);
    }

    /**
     * 查看服务报告费用详情2
     *
     * @param
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/10 11:03 上午
     */
    @Override
    public ResponseWithData<?> detailServiceReportFee2(String serviceNo, Long enginnerId, String helpId, String bu, String prov, String city, Double chargeHours) {
        double partsTotallFee = reportPortMapper.selectReportPortsPrices(serviceNo, helpId, "1");
        StCost cost = null;
        StServiceReport serviceReport = stServiceReportMapper.selectStServiceReportByServiceNoAndHelpId(serviceNo, helpId);
        //特殊费用
        JSONObject checkServiceEspecial = ccService.CheckServiceEspecial(serviceNo);
        //基础费用
        JSONObject response = ccService.GetServiceCharge(enginnerId + "", bu, prov, city);

        //第一次费用保存
        JSONObject fistcheck = (JSONObject) checkServiceEspecial.getJSONArray("record").get(0);
        StCost stCost = new StCost();
        stCost.setFeeBalanceType(fistcheck.getString("FeeBalanceType"));
        if (fistcheck.getString("EspeciallyFee") == null) {
            stCost.setEspeciallyFee(0);
        } else {
            stCost.setEspeciallyFee(new Double(fistcheck.getString("EspeciallyFee")));
        }
        if (fistcheck.getString("EspeFeeDesc") == null) {
            stCost.setEspeFeeDesc("");
        } else {
            stCost.setEspeFeeDesc(fistcheck.getString("EspeFeeDesc"));
        }

        JSONArray ccFeeArrayFirst = response.getJSONArray("record");
        if (!ObjectUtils.isEmpty(ccFeeArrayFirst)) {
            JSONObject fisetccFee = (JSONObject) ccFeeArrayFirst.get(0);
            stCost.setBasicFee(new Double(fisetccFee.getString("basic_fee")));
            stCost.setHourFee(new Double(fisetccFee.getString("hour_fee")));
            stCost.setMinHour(new Double(fisetccFee.getString("min_hour")));
        }
        stCost.setServiceNo(serviceNo);
        stCost.setFse(enginnerId + "");
        stCost.setHelpId(helpId);
        List<StCost> stCostList = stCostMapper.selectStCostList(stCost);
        if (stCostList.size() < 1) {
            stCostMapper.insertStCost(stCost);
            cost = stCost;
        } else {
            cost = stCostList.get(0);
        }
        //第一次费用保存结束
        // 查询

        Map<String, Object> data = new HashMap<>();
        if (cost != null) {
            if ("0".equals(cost.getFeeBalanceType())) {
                if (serviceReport != null) {
                    data.put("manHours", (double) Math.round(serviceReport.getManHours() * 100) / 100);//人工小时
                    data.put("manRate", serviceReport.getManRate());//人工费用
                    data.put("totalPrice", (double) Math.round(serviceReport.getTotalPrice() * 100) / 100);//人工总费用

                    data.put("travelStayPrice", (double) Math.round(serviceReport.getTravelStayPrice() * 100) / 100);//旅途住宿费用
                    data.put("manTotal", (double) Math.round(serviceReport.getManTotal() * 100) / 100);//人工和旅途住宿费总费用
                    data.put("feeBalanceType", cost.getFeeBalanceType());//type
                    data.put("partsTotallFee", (double) Math.round(partsTotallFee * 100) / 100);//备件费用 ************
                    data.put("totalBilled", (double) Math.round(partsTotallFee + serviceReport.getManTotal() * 100) / 100);//报告总费用
                } else {
                    data.put("manHours", 0);//人工小时
                    data.put("manRate", 0);//人工费用
                    data.put("totalPrice", 0);//人工总费用
                    data.put("travelStayPrice", 0);//旅途住宿费用
                    data.put("manTotal", 0);//人工和旅途住宿费总费用
                    //data.put("especiallyFee", cost.getBasicFee());//特殊费用
                    data.put("feeBalanceType", cost.getFeeBalanceType());//type
                    data.put("partsTotallFee", 0);//备件费用 ************
                    data.put("totalBilled", 0);//报告总费用
                }

            }
            if ("1".equals(cost.getFeeBalanceType())) {
                BigDecimal hourstemp = BigDecimal.valueOf(chargeHours - cost.getMinHour()).divide(new BigDecimal("1".toString()), 2, BigDecimal.ROUND_HALF_UP);
                ;
                if (hourstemp.compareTo(BigDecimal.ZERO) <= 0) {
                    hourstemp = new BigDecimal("0.0");
                }
                data.put("manHours", hourstemp);//人工小时
                data.put("manRate", cost.getHourFee());//人工费用
                data.put("totalPrice", hourstemp.multiply(BigDecimal.valueOf(cost.getHourFee())).divide(new BigDecimal("1".toString()), 2, BigDecimal.ROUND_HALF_UP));//人工总费用

                double basicFee = 0;
                if (chargeHours == 0) {
                    basicFee = 0;
                    data.put("basicFee", basicFee);//基本费用
                } else {
                    basicFee = cost.getBasicFee();
                    data.put("basicFee", basicFee);//基本费用
                }
                data.put("feeBalanceType", cost.getFeeBalanceType());//type
                BigDecimal manTotal = (hourstemp.multiply(BigDecimal.valueOf(cost.getHourFee())).add(BigDecimal.valueOf(basicFee)));//人工和旅途住宿总费
                data.put("manTotal", manTotal);//人工总费用
                data.put("partsTotallFee", partsTotallFee);//备件费用
                data.put("totalBilled", manTotal.add(BigDecimal.valueOf(basicFee)).add(BigDecimal.valueOf(partsTotallFee)).divide(new BigDecimal("1".toString()), 2, BigDecimal.ROUND_HALF_UP));//报告总费用
            }
            if ("2".equals(cost.getFeeBalanceType())) {

                if (cost.getBasicFee() > 0) {
                    BigDecimal hourstemp = BigDecimal.valueOf(chargeHours - cost.getMinHour()).divide(new BigDecimal("1".toString()), 2, BigDecimal.ROUND_HALF_UP);
                    ;
                    if (hourstemp.compareTo(BigDecimal.ZERO) <= 0) {
                        hourstemp = new BigDecimal("0.0");
                    }
                    data.put("manHours", hourstemp);//人工小时
                    data.put("manRate", cost.getHourFee());//人工费用
                    data.put("totalPrice", hourstemp.multiply(BigDecimal.valueOf(cost.getHourFee())).divide(new BigDecimal("1".toString()), 2, BigDecimal.ROUND_HALF_UP));//人工总费用

                    double basicFee = 0;
                    if (chargeHours == 0) {
                        basicFee = 0;
                        if (cost.getBasicFee() > 0) {
                            data.put("basicFee", cost.getBasicFee());//基本费用
                        } else {
                            data.put("basicFee", basicFee);//基本费用
                        }
                    } else {
                        basicFee = cost.getBasicFee();
                        data.put("basicFee", basicFee);//基本费用
                    }


                    BigDecimal manTotal = (hourstemp.multiply(BigDecimal.valueOf(cost.getHourFee())).add(BigDecimal.valueOf(basicFee)));//人工和旅途住宿总费
                    data.put("manTotal", manTotal.divide(new BigDecimal("1".toString()), 2, BigDecimal.ROUND_HALF_UP));//人工总费用

                    data.put("especiallyFee", cost.getEspeciallyFee());//特殊费用
                    data.put("partsTotallFee", partsTotallFee);//备件费用
                    data.put("totalBilled", manTotal.add(BigDecimal.valueOf(basicFee)).add(BigDecimal.valueOf(cost.getEspeciallyFee())).add(BigDecimal.valueOf(partsTotallFee)).divide(new BigDecimal("1".toString()), 1, BigDecimal.ROUND_HALF_UP));//报告总费用
                    data.put("feeBalanceType", cost.getFeeBalanceType());//type
                } else {
                    if (serviceReport != null) {
                        data.put("manHours", serviceReport.getManHours());//人工小时
                        data.put("manRate", (double) Math.round(serviceReport.getManRate() * 100) / 100);//人工费用
                        data.put("totalPrice", (double) Math.round(serviceReport.getTotalPrice() * 100) / 100);//人工总费用
                        data.put("feeBalanceType", cost.getFeeBalanceType());//type
                        data.put("travelStayPrice", (double) Math.round(serviceReport.getTravelStayPrice() * 100 / 100));//旅途住宿费用
                        data.put("manTotal", (double) Math.round(serviceReport.getManTotal() * 100) / 100);//人工和旅途住宿费总费用
                        data.put("especiallyFee", (double) Math.round(cost.getEspeciallyFee() * 100) / 100);//特殊费用
                        data.put("partsTotallFee", (double) Math.round(partsTotallFee * 100) / 100);//备件费用 ************
                        data.put("totalBilled", (double) Math.round((partsTotallFee + cost.getBasicFee() + serviceReport.getManTotal()) * 100) / 100);//报告总费用
                    } else {
                        data.put("manHours", 0);//人工小时
                        data.put("manRate", 0);//人工费用
                        data.put("totalPrice", 0);//人工总费用
                        data.put("travelStayPrice", 0);//旅途住宿费用
                        data.put("manTotal", 0);//人工和旅途住宿费总费用
                        data.put("especiallyFee", cost.getEspeciallyFee());//特殊费用
                        data.put("feeBalanceType", cost.getFeeBalanceType());//type
                        data.put("partsTotallFee", 0);//备件费用 ************
                        data.put("totalBilled", cost.getBasicFee());//报告总费用
                    }
                }

//                data.put("manHours", serviceReport.getManHours());//人工小时
//                data.put("manRate", serviceReport.getManRate());//人工费用
//                data.put("totalPrice", serviceReport.getTotalPrice());//人工总费用
//                data.put("travelStayPrice", serviceReport.getTravelStayPrice());//旅途住宿费用
//                data.put("manTotal", serviceReport.getManTotal());//人工和旅途住宿费总费用
//                data.put("especiallyFee", serviceReport.getEspeciallyFee());//特殊费用
//                data.put("partsTotallFee", serviceReport.getPartsTotallFee());//备件费用
//                data.put("totalBilled", serviceReport.getTotalBilled());//报告总费用
//                data.put("feeBalanceType", serviceReport.getFeeBalanceType());
//                data.put("chargeHours", serviceReport.getChargeHours());//收费小时数
//                data.put("basicFee", serviceReport.getBasicFee());//基本费用
//                data.put("min_hour", serviceReport.getMinHour());
            }

        }
        return new ResponseWithData<>().success(data).code(200);
    }


    /**
     * 2.25验收签名照片、发送 邮件
     *
     * @param serviceNo
     * @param reportGuid
     * @param enginnerId
     * @param signPhotoName
     * @param b
     * @param isSendEmail
     * @param emailAddress
     * @methodName: signPicAndSendEmailSubmithandle
     * @description: TODO
     * @return: okhttp3.Response
     * @author: shihx
     * @date: 2020-04-10 9:23
     **/
    public JSONObject signPicAndSendEmailSubmithandle(String serviceNo, String reportGuid, String
            enginnerId, String signPhotoName, String b, String isSendEmail, String emailAddress) {
        JSONObject jsonObject = new JSONObject();
        String ccServerUrl = global.getCcServerUrl();
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("service_no", serviceNo);
        builder.add("report_guid", reportGuid);
        builder.add("enginner_id", enginnerId);
        builder.add("sign_photo_name", signPhotoName);
        builder.add("b", b);
        builder.add("is_send_email", isSendEmail);
        builder.add("email_address", emailAddress);
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        url.append("signPicAndSendEmailSubmit.asmx/signPicAndSendEmailSubmithandle");
        /** 先保存接口参数 */
        InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
        interfaceOperationLog.setInterfaceName("2.25验收签名照片、发送 邮件");
        interfaceOperationLog.setInterfaceType("signPicAndSendEmailSubmithandle");
        interfaceOperationLog.setInterfaceUrl(url.toString());
        interfaceOperationLog.setFseId(enginnerId);
        interfaceOperationLog.setInterfaceRequest("serviceNo:" + serviceNo + ",reportGuid:" + reportGuid + ",enginnerId:" + enginnerId + ",signPhotoName:" + signPhotoName + ",b:" + b + ",isSendEmail:" + isSendEmail + ",emailAddress:" + emailAddress);
        interfaceOperationLog.setStartTime(new Date());
        iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

        Response res = null;
        String interfaceResponse = "";
        String interfaceResponseBody = "";
        String interfaceState = "";
        try {
            /** 调用CC端接口 */
            res = OkHttpUtils.getInstance().postRequest(url.toString(), builder.build());
            interfaceResponse = res.toString();
            interfaceResponseBody = res.body().string();
            interfaceResponse += " Body参数：" + interfaceResponseBody;
            log.info("调用CC端返回结果：" + interfaceResponseBody);
            if (res.code() == 200) {
                interfaceState = "1";
            } else {
                interfaceState = "2";
            }
        } catch (Exception e) {
            log.info("调用CC端返回结果：" + interfaceResponseBody);
            interfaceResponse = e.getMessage();
            interfaceState = "0";
        }

        /** 更新接口返回结果 */
        interfaceOperationLog.setEndTime(new Date());
        interfaceOperationLog.setInterfaceResponse(interfaceResponse);
        interfaceOperationLog.setInterfaceState(interfaceState);
        iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

        /** 如果调用接口异常直接返回 */
        if ("0".equals(interfaceState)) {
            jsonObject.put("state", 202);
            jsonObject.put("msg", "签名失败 验收签名照片、发送邮件接口发生异常");
            jsonObject.put("data", interfaceResponseBody);
            return jsonObject;
        }
        if (res != null) {
            if (res.code() == 200) {
                JSONObject obj = JSON.parseObject(interfaceResponseBody);
                if ("1".equals(obj.getString("status"))) {
                    jsonObject.put("state", 200);
                    jsonObject.put("msg", "签名成功");
                    jsonObject.put("data", interfaceResponseBody);
                    return jsonObject;
                }
            }
        }
        jsonObject.put("state", 201);
        jsonObject.put("msg", "签名失败 验收签名照片、发送邮件接口发生异常");
        jsonObject.put("data", interfaceResponseBody);
        return jsonObject;
    }

    /**
     * 2.26验收签名照片、发送 邮件
     *
     * @param serviceNo
     * @param reportGuid
     * @param enginnerId
     * @param signPhotoName
     * @param b
     * @param isSendEmail
     * @param emailAddress
     * @methodName: inssignPicAndSendEmailSubmit
     * @description: TODO
     * @return: okhttp3.Response
     * @author: shihx
     * @date: 2020-04-10 9:24
     **/
    public JSONObject inssignPicAndSendEmailSubmit(String serviceNo, String reportGuid, String
            enginnerId, String signPhotoName, String b, String isSendEmail, String emailAddress) {
        JSONObject jsonObject = new JSONObject();
        String ccServerUrl = global.getCcServerUrl();
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("service_no", serviceNo);
        builder.add("report_guid", reportGuid);
        builder.add("enginner_id", enginnerId);
        builder.add("sign_photo_name", signPhotoName);
        builder.add("b", b);
        builder.add("is_send_email", isSendEmail);
        builder.add("email_address", emailAddress);
        StringBuffer url = new StringBuffer();
        url.append(ccServerUrl);
        //  url.append("inssignPicAndSendEmailSubmit.asmx/inssignPicAndSendEmailSubmit");
        url.append("InssignPicAndSendEmailSubmit.asmx/InssignPicAndSendEmailSubmitHanle");


        /** 先保存接口参数 */
        InterfaceOperationLog interfaceOperationLog = new InterfaceOperationLog();
        interfaceOperationLog.setInterfaceName("2.26验收签名照片、发送 邮件");
        interfaceOperationLog.setInterfaceType("InssignPicAndSendEmailSubmit");
        interfaceOperationLog.setInterfaceUrl(url.toString());
        interfaceOperationLog.setFseId(enginnerId);
        interfaceOperationLog.setInterfaceRequest("serviceNo:" + serviceNo + ",reportGuid:" + reportGuid + ",enginnerId:" + enginnerId + ",signPhotoName:" + signPhotoName + ",b:" + b + ",isSendEmail:" + isSendEmail + ",emailAddress:" + emailAddress);
        interfaceOperationLog.setStartTime(new Date());
        iInterfaceOperationLogService.insertInterfaceOperationLog(interfaceOperationLog);

        Response res = null;
        String interfaceResponse = "";
        String interfaceResponseBody = "";
        String interfaceState = "";
        try {
            /** 调用CC端接口 */
            res = OkHttpUtils.getInstance().postRequest(url.toString(), builder.build());
            interfaceResponse = res.toString();
            interfaceResponseBody = res.body().string();
            interfaceResponse += " Body参数：" + interfaceResponseBody;
            log.info("调用CC端返回结果：" + interfaceResponseBody);
            if (res.code() == 200) {
                interfaceState = "1";
            } else {
                interfaceState = "2";
            }
        } catch (Exception e) {
            log.info("调用CC端返回结果：" + interfaceResponseBody);
            interfaceResponse = e.getMessage();
            interfaceState = "0";
        }

        /** 更新接口返回结果 */
        interfaceOperationLog.setEndTime(new Date());
        interfaceOperationLog.setInterfaceResponse(interfaceResponse);
        interfaceOperationLog.setInterfaceState(interfaceState);
        iInterfaceOperationLogService.updateInterfaceOperationLog(interfaceOperationLog);

        /** 如果调用接口异常直接返回 */
        if ("0".equals(interfaceState)) {
            jsonObject.put("state", 202);
            jsonObject.put("msg", "签名失败 验收签名照片、发送邮件接口发生异常");
            jsonObject.put("data", interfaceResponseBody);
            return jsonObject;
        }
        if (res != null) {
            if (res.code() == 200) {
                JSONObject obj = JSON.parseObject(interfaceResponseBody);
                if ("1".equals(obj.getString("status"))) {
                    jsonObject.put("state", 200);
                    jsonObject.put("msg", "签名成功");
                    jsonObject.put("data", interfaceResponseBody);
                    return jsonObject;
                }
            }
        }
        jsonObject.put("state", 201);
        jsonObject.put("msg", "签名失败 验收签名照片、发送邮件接口发生异常");
        jsonObject.put("data", interfaceResponseBody);
        return jsonObject;
    }


}
